https://codechacha.com/ko/java-collections-hashset/ 기초
>순서X, duplicate X
>Index X -> 일일히 객체 서로 비교한다. -> so List보다 느리다.
>why HashSet?
접속사수 구할때 이용(동일 IP는 1번만 카운트한다.- duplicat X) ex) print all memebers!
>HashSet은 중복불가 인데,다른 object(reference/key) = 같은 값(value)을, HashSet.add(object)했을때,
중복으로 인식안하고 각각으로 인식해서 count 2번함.
set.add(object1);
set.add(object2); 근데 object1, object2의 값이 "Pluto"로 같은경우
-> eqauls/HashCode method 이용하여 중복불가로하여, 한번만 count되게 한다.
eqauls: 두객체의 내용이 같은지(equality)
hashcode:두 객체가 동일 객체냐(identity)
<equals/HashCode>
object1, objec2는 hashcode를 통해 bucket2를 향한다.
기본define 예)
private final Set<HeavenlyBody> satellites = new HashSet<>();
[Main]
object.add(); 값추가.
for(HeavenlyBody moon : moons) { 출력(for문 이용경우)
System.out.println("\t" + moon.getName());
}
예제)
MAP이용하여 to store all object key -> define hashSet.
천체 - 태양계 - 위성 - moon
HeavenlyBody Class
package com.timbuchalka;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
/**
* Created by dev on 12/01/2016.
*/
public final class HeavenlyBody {
private final String name; //field
private final double orbitalPeriod;
private final Set<HeavenlyBody> satellites; //data save //hashSet define. V
//constructor
public HeavenlyBody(String name, double orbitalPeriod) {
this.name = name;
this.orbitalPeriod = orbitalPeriod;
this.satellites = new HashSet<>(); // V
}
//getter
public String getName() {
return name;
}
public double getOrbitalPeriod() {
return orbitalPeriod;
}
//add method
public boolean addMoon(HeavenlyBody moon) { //위성에 달 추가// hashSet.add v
return this.satellites.add(moon);
}
//hashSet getter
public Set<HeavenlyBody> getSatellites() { // V
return new HashSet<>(this.satellites); //It's own object for security reasons.
}
Main - Output
package com.timbuchalka;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class Main {
private static Map<String, HeavenlyBody> solarSystem = new HashMap<>();//Map data save
private static Set<HeavenlyBody> planets = new HashSet<>(); //Set data save
public static void main(String[] args) {
// 값설정
HeavenlyBody temp = new HeavenlyBody("Mercury", 88); //object 1 // call constructor
solarSystem.put(temp.getName(), temp); //Map(key,value) : 태양계에 추가
planets.add(temp); //Set(key) : 행성에 추가
temp = new HeavenlyBody("Venus", 225); //object1의 또다른 공간
solarSystem.put(temp.getName(), temp); //태양계에
planets.add(temp); //행성에
temp = new HeavenlyBody("Earth", 365); //object1의 또다른 공간
solarSystem.put(temp.getName(), temp); //태양계에
planets.add(temp); //행성에
//moon define
HeavenlyBody tempMoon = new HeavenlyBody("Moon", 27); //object 2
solarSystem.put(tempMoon.getName(), tempMoon); //Map태양계에
temp.addMoon(tempMoon);
//Mars + moon추가
temp = new HeavenlyBody("Mars", 687); //object1의 또다른 공간
solarSystem.put(temp.getName(), temp); //태양계에
planets.add(temp); //행성에
tempMoon = new HeavenlyBody("Deimos", 1.3); //object1의 또다른 공간
solarSystem.put(tempMoon.getName(), tempMoon);
temp.addMoon(tempMoon); // temp is still Mars
tempMoon = new HeavenlyBody("Phobos", 0.3); //object1의 또다른 공간
solarSystem.put(tempMoon.getName(), tempMoon);
temp.addMoon(tempMoon); // temp is still Mars
//Jupiter + moon 추가
temp = new HeavenlyBody("Jupiter", 4332);
solarSystem.put(temp.getName(), temp);
planets.add(temp);
tempMoon = new HeavenlyBody("Io", 1.8);
solarSystem.put(tempMoon.getName(), tempMoon);
temp.addMoon(tempMoon); // temp is still Jupiter
tempMoon = new HeavenlyBody("Europa", 3.5);
solarSystem.put(tempMoon.getName(), tempMoon);
temp.addMoon(tempMoon); // temp is still Jupiter
tempMoon = new HeavenlyBody("Ganymede", 7.1);
solarSystem.put(tempMoon.getName(), tempMoon);
temp.addMoon(tempMoon); // temp is still Jupiter
tempMoon = new HeavenlyBody("Callisto", 16.7);
solarSystem.put(tempMoon.getName(), tempMoon);
temp.addMoon(tempMoon); // temp is still Jupiter
//Saturn
temp = new HeavenlyBody("Saturn", 10759);
solarSystem.put(temp.getName(), temp);
planets.add(temp);
//Uranus
temp = new HeavenlyBody("Uranus", 30660);
solarSystem.put(temp.getName(), temp);
planets.add(temp);
//Neptune
temp = new HeavenlyBody("Neptune", 165);
solarSystem.put(temp.getName(), temp);
planets.add(temp);
//Pluto
temp = new HeavenlyBody("Pluto", 248);
solarSystem.put(temp.getName(), temp);
planets.add(temp);
//print
System.out.println("Planets");
for(HeavenlyBody planet : planets) {
System.out.println("\t" + planet.getName());
}
//Mars 출력
HeavenlyBody body = solarSystem.get("Mars");
System.out.println("Moons of " + body.getName());
for(HeavenlyBody jupiterMoon: body.getSatellites()) {
System.out.println("\t" + jupiterMoon.getName());
}
//moon 출력
Set<HeavenlyBody> moons = new HashSet<>();
for(HeavenlyBody planet : planets) {
moons.addAll(planet.getSatellites());
}
System.out.println("All Moons");
for(HeavenlyBody moon : moons) {
System.out.println("\t" + moon.getName());
}
}
}
//Output
D:\IT\JDK\jdk11.0.6_10\bin\java.exe "-javaagent:D:\IT\IDEA\IntelliJ IDEA Community Edition 2020.1\lib\idea_rt.jar=50358:D:\IT\IDEA\IntelliJ IDEA Community Edition 2020.1\bin" -Dfile.encoding=UTF-8 -classpath D:\IT\Java-Collections-Sets-&-HashSet-Source-code\out\production\SetAndHashSet com.timbuchalka.Main
Planets
Mercury
Venus
Saturn
Neptune
Earth
Jupiter
Uranus
Mars
Pluto
Moons of Mars
Phobos
Deimos
All Moons
Moon
Ganymede
Phobos
Deimos
Europa
Callisto
Io
Process finished with exit code 0
다른 Reference(object,key)/동일name 값 한번만 count되게, equals/HashCode 이용
object tem : "Pluto"
object pluto : "Pluto" -> 한번만 count 되게.(name의 equals/HashCode)
-> object tem의 name "Pluto" 값(248)한번정해지면 끝.count No.
참고) subclass와 비교되는 등(오류발생)이 발생할수 있으니, final로
Class자체를 final로 define하던가,
Class가 일반적이면, equals/hashcode를 final로 define하던가 하면 됨.
package com.timbuchalka;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public final class HeavenlyBody { //fINAL CLASS로 define. V
private final String name; //field
private final double orbitalPeriod;
private final Set<HeavenlyBody> satellites; //data save //hashSet define.
//constructor
public HeavenlyBody(String name, double orbitalPeriod) {
this.name = name;
this.orbitalPeriod = orbitalPeriod;
this.satellites = new HashSet<>(); //
}
//getter
public String getName() {
return name;
}
public double getOrbitalPeriod() {
return orbitalPeriod;
}
//add method
public boolean addMoon(HeavenlyBody moon) { //위성에 달 추가// hashSet.add
return this.satellites.add(moon);
}
//hashSet getter
public Set<HeavenlyBody> getSatellites() { //
return new HashSet<>(this.satellites); //It's own object for security reasons.
}
//equals and hashcode. 자동완성 generate
// 다른object, 같은 이름을 반복불가로 해야하니, "name"의 equals and hashcode generate해야함. V
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
HeavenlyBody that = (HeavenlyBody) o;
return Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
//아래는 샘이 manually로 함 작성한거
// public boolean equals(Object obj) {
// if(this == obj) {
// return true;
// }
//
// System.out.println("obj.getClass() is " + obj.getClass());
// System.out.println("this.getClass() is " + this.getClass());
// if ((obj == null) || (obj.getClass() != this.getClass())) {
// return false;
// }
//
// String objName = ((HeavenlyBody) obj).getName();
// return this.name.equals(objName);
// }
}
Main // Output
package com.timbuchalka;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class Main {
private static Map<String, HeavenlyBody> solarSystem = new HashMap<>();
private static Set<HeavenlyBody> planets = new HashSet<>();
public static void main(String[] args) {
HeavenlyBody temp = new HeavenlyBody("Mercury", 88);
solarSystem.put(temp.getName(), temp);
planets.add(temp);
temp = new HeavenlyBody("Venus", 225);
solarSystem.put(temp.getName(), temp);
planets.add(temp);
temp = new HeavenlyBody("Earth", 365);
solarSystem.put(temp.getName(), temp);
planets.add(temp);
HeavenlyBody tempMoon = new HeavenlyBody("Moon", 27);
solarSystem.put(tempMoon.getName(), tempMoon);
temp.addMoon(tempMoon);
temp = new HeavenlyBody("Mars", 687);
solarSystem.put(temp.getName(), temp);
planets.add(temp);
tempMoon = new HeavenlyBody("Deimos", 1.3);
solarSystem.put(tempMoon.getName(), tempMoon);
temp.addMoon(tempMoon); // temp is still Mars
tempMoon = new HeavenlyBody("Phobos", 0.3);
solarSystem.put(tempMoon.getName(), tempMoon);
temp.addMoon(tempMoon); // temp is still Mars
temp = new HeavenlyBody("Jupiter", 4332);
solarSystem.put(temp.getName(), temp);
planets.add(temp);
tempMoon = new HeavenlyBody("Io", 1.8);
solarSystem.put(tempMoon.getName(), tempMoon);
temp.addMoon(tempMoon); // temp is still Jupiter
tempMoon = new HeavenlyBody("Europa", 3.5);
solarSystem.put(tempMoon.getName(), tempMoon);
temp.addMoon(tempMoon); // temp is still Jupiter
tempMoon = new HeavenlyBody("Ganymede", 7.1);
solarSystem.put(tempMoon.getName(), tempMoon);
temp.addMoon(tempMoon); // temp is still Jupiter
tempMoon = new HeavenlyBody("Callisto", 16.7);
solarSystem.put(tempMoon.getName(), tempMoon);
temp.addMoon(tempMoon); // temp is still Jupiter
temp = new HeavenlyBody("Saturn", 10759);
solarSystem.put(temp.getName(), temp);
planets.add(temp);
temp = new HeavenlyBody("Uranus", 30660);
solarSystem.put(temp.getName(), temp);
planets.add(temp);
temp = new HeavenlyBody("Neptune", 165);
solarSystem.put(temp.getName(), temp);
planets.add(temp);
temp = new HeavenlyBody("Pluto", 248); // object(temp), name: "Pluto" V
solarSystem.put(temp.getName(), temp);
planets.add(temp); //set planet에 add V
System.out.println("Planets");
for(HeavenlyBody planet : planets) {
System.out.println("\t" + planet.getName());
}
HeavenlyBody body = solarSystem.get("Mars");
System.out.println("Moons of " + body.getName());
for(HeavenlyBody jupiterMoon: body.getSatellites()) {
System.out.println("\t" + jupiterMoon.getName());
}
Set<HeavenlyBody> moons = new HashSet<>();
for(HeavenlyBody planet : planets) {
moons.addAll(planet.getSatellites());
}
System.out.println("All Moons");
for(HeavenlyBody moon : moons) {
System.out.println("\t" + moon.getName());
}
HeavenlyBody pluto = new HeavenlyBody("Pluto", 842); //object(pluto), name: "Pluto" V
planets.add(pluto); // Set planet에 add V
// 842로 값 변경 No. count No.
for(HeavenlyBody planet : planets) {
System.out.println(planet.getName() + ": " + planet.getOrbitalPeriod());
}
//설명위한 코드.
//Object o = new Object();
// o.equals(o);
// "pluto".equals("");
}
}
//Output
D:\IT\JDK\jdk11.0.6_10\bin\java.exe "-javaagent:D:\IT\IDEA\IntelliJ IDEA Community Edition 2020.1\lib\idea_rt.jar=50450:D:\IT\IDEA\IntelliJ IDEA Community Edition 2020.1\bin" -Dfile.encoding=UTF-8 -classpath "D:\IT\Java-Collections-HashSet-equals()-and-hashCode()-Source-code\out\production\SetAndHashSet" com.timbuchalka.Main
Planets
Mars
Neptune
Earth
Jupiter
Saturn
Venus
Uranus
Pluto
Mercury
Moons of Mars
Deimos
Phobos
All Moons
Deimos
Moon
Io
Europa
Callisto
Ganymede
Phobos
Mars: 687.0
Neptune: 165.0
Earth: 365.0
Jupiter: 4332.0
Saturn: 10759.0
Venus: 225.0
Uranus: 30660.0
Pluto: 248.0 // Pluto 한번만 count됨/ 값은 처음값 그대로. V
Mercury: 88.0
Process finished with exit code 0
참고) hashSet, TreeSet
'JavaCode(review)' 카테고리의 다른 글
InstanceOF (0) | 2020.07.14 |
---|---|
Set - Symmetric&Asymmetric ( Set Interface Bulk Operation) - collection (0) | 2020.07.13 |
Immutable class // Location Class- adventure game 이용 (0) | 2020.07.07 |
Spring split method (0) | 2020.07.07 |
Map Interface - Collection - Adventure Game Challenge. (0) | 2020.07.06 |