當前位置:編程學習大全網 - 編程軟體 - java編程的例子

java編程的例子

//********************學生

導入Java . util . objects;

公共課學生{

公共字符串名稱;

公共int age

學生(){}

學生(字符串名稱,整數年齡){

this.name = name

this.age =年齡;

}

公共字符串toString(){//覆蓋toString()

返回“姓名:“+姓名+”年齡:“+年齡;

}

public boolean equals(object o){//覆蓋equals()。

if (this == o)返回true

if (o == null || getClass()!= o.getClass())返回false

學生學生=(學生)o;

返回年齡==學生年齡& amp& ampObjects.equals(name,student . name);

}

Public int hashCode() {//覆蓋hashCode()

return objects . hash(name)+age;

}

}

//* * * * * * * * * * * * * * * * * * * *學生測試

導入Java . util . hashset;

公共課學生測試{

公共靜態void main(String[] args) {

HashSet & lt學生& gths=new HashSet<。& gt();

學生s 1 =新生(" zs ",19);//s1

學生s2 =新生(“zs”,19);//s2

學生s3 =新生(" ls ",19);//s3

hs . add(s 1);//加入集合

hs . add(S2);//

hs . add(S3);//

//s1,s2,equals()返回true,s2不會添加到集合中。

For(學生it:hs) {//遍歷HasSet。

system . out . println(it);

}

}

}

  • 上一篇:VC簡單編程
  • 下一篇:面向對象和面向過程
  • copyright 2024編程學習大全網