24 April 2016

Nhận biết tên và địa chỉ của 1 người trong hashSet


Main.java
package edu.aptech1;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

public class Main {
 @SuppressWarnings("unused")
 public static void main(String[] args) {
  ArrayList<String> list = new ArrayList<String>();
  Student a = new Student("Ngoc", "Ha Noi", 111);
  Student b = new Student("Ngoc", "Ho Chi Minh", 11);
  Student c = new Student("Ngoc", "Ho Chi Minh", 1111);

  Set<Student> s = new HashSet<Student>();
  s.add(a);
  s.add(b);
  s.add(c);
  System.out.println("Set size: " + s.size());
  for(Student s1 : s){
   System.out.println(s1.getName() +" "+s1.getLocation()+" "+s1.getMoney());
  }

 }

}
Student.java
package edu.aptech1;

public class Student {
 private String name;
 private String location;
 private int money;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public Student(String name) {
  super();
  this.name = name;
 }

 public Student() {
  super();
 }

 public String getLocation() {
  return location;
 }

 public void setLocation(String location) {
  this.location = location;
 }

 public int getMoney() {
  return money;
 }

 public void setMoney(int money) {
  this.money = money;
 }

 public Student(String name, String location, int money) {
  super();
  this.name = name;
  this.location = location;
  this.money = money;
 }

 @Override
 public int hashCode() {
  return location.hashCode(); // location hay name --> ok
 }

 @Override
 public boolean equals(Object obj) {
  if (!(obj instanceof Student)) {
   return false;
  }
  Student s = (Student) obj;
  if (s.getName() == null || s.getLocation() == null) {
   return false;
  }
  return s.getName().equals(name) && s.getLocation().equals(location) && getMoney() == money;
 }
}


                    
                    
                    
                  

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang