LinkedList<String> linkedList = new LinkedList<>(); linkedList.add("a"); linkedList.add("a"); linkedList.add("b"); linkedList.add("a"); linkedList.addFirst("0"); linkedList.addLast("9"); System.out.println(linkedList); linkedList.removeLast(); System.out.println(linkedList); linkedList.removeFirst(); System.out.println(linkedList); String first = linkedList.getFirst(); System.out.println(first); String last = linkedList.getLast(); System.out.println(last); boolean b = linkedList.isEmpty(); System.out.println(b);
package com.Set集合; public class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Person(String name, int age) { super(); this.name = name; this.age = age; } public Person() { super(); // TODO Auto-generated constructor stub } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } }
這裡注意我們需要重寫HashClod方法與equlas()方法 當然在打印的時候需要重寫toString()方法
public static void main(String[] args) { HashSet<Person> hashSet = new HashSet<>(); hashSet.add(new Person("張三",12)); hashSet.add(new Person("李四",12)); hashSet.add(new Person("張三",12)); hashSet.add(new Person("張三",21)); // System.out.println(hashSet); Iterator<Person> iterator =hashSet.iterator(); while(iterator.hasNext()){ Person next = iterator.next(); System.out.println(next); } } }
//執行結果為:張三 12
李四 12
張三 21
public class Demo02_LinkedHashSet { public static void main(String[] args) { LinkedHashSet<String> hashSet = new LinkedHashSet<>(); hashSet.add("a"); hashSet.add("b"); hashSet.add("c"); hashSet.add("d"); //增強for遍歷 for (String string : hashSet) { System.out.print(string+" "); } //迭代器遍歷 Iterator<String> iterator = hashSet.iterator(); while(iterator.hasNext()){ String str = iterator.next(); System.out.println(str); } System.out.println(hashSet); }