Java Tutorial/Collections/LinkedHashSet
Содержание
Get Size of Java LinkedHashSet
import java.util.LinkedHashSet;
public class Main {
public static void main(String[] args) {
LinkedHashSet<Integer> lhashSet = new LinkedHashSet<Integer>();
System.out.println("Size of LinkedHashSet : " + lhashSet.size());
lhashSet.add(new Integer("1"));
lhashSet.add(new Integer("2"));
lhashSet.add(new Integer("3"));
System.out.println(lhashSet.size());
lhashSet.remove(new Integer("1"));
System.out.println(lhashSet.size());
}
}
Iterate through elements of Java LinkedHashSet
import java.util.Iterator;
import java.util.LinkedHashSet;
public class Main {
public static void main(String[] args) {
LinkedHashSet<Integer> lhashSet = new LinkedHashSet<Integer>();
lhashSet.add(new Integer("1"));
lhashSet.add(new Integer("2"));
lhashSet.add(new Integer("3"));
Iterator itr = lhashSet.iterator();
while (itr.hasNext()){
System.out.println(itr.next());
}
}
}
Putting your own type in a LinkedHashSet
import java.util.LinkedHashSet;
import java.util.Set;
public class MainClass {
public static Set fill(Set a, int size) {
for (int i = 0; i < size; i++)
a.add(new MyType(i));
return a;
}
public static void test(Set a) {
fill(a, 10);
fill(a, 10); // Try to add duplicates
fill(a, 10);
System.out.println(a);
}
public static void main(String[] args) {
test(new LinkedHashSet());
}
}
class MyType implements Comparable {
private int i;
public MyType(int n) {
i = n;
}
public boolean equals(Object o) {
return (o instanceof MyType) && (i == ((MyType) o).i);
}
public int hashCode() {
return i;
}
public String toString() {
return i + " ";
}
public int compareTo(Object o) {
int i2 = ((MyType) o).i;
return (i2 < i ? -1 : (i2 == i ? 0 : 1));
}
}
//
[0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
Remove all elements from Java LinkedHashSet
import java.util.LinkedHashSet;
public class Main {
public static void main(String[] args) {
LinkedHashSet<Integer> lhashSet = new LinkedHashSet<Integer>();
lhashSet.add(new Integer("1"));
lhashSet.add(new Integer("2"));
lhashSet.add(new Integer("3"));
System.out.println(lhashSet);
lhashSet.clear();
System.out.println(lhashSet);
System.out.println(lhashSet.isEmpty());
}
}
Remove specified element from Java LinkedHashSet
import java.util.LinkedHashSet;
public class Main {
public static void main(String[] args) {
LinkedHashSet<Integer> lhashSet = new LinkedHashSet<Integer>();
lhashSet.add(new Integer("1"));
lhashSet.add(new Integer("2"));
lhashSet.add(new Integer("3"));
System.out.println(lhashSet);
boolean blnRemoved = lhashSet.remove(new Integer("2"));
System.out.println(blnRemoved);
System.out.println(lhashSet);
}
}