1.使用集合框架LinkedList实现堆栈效果
public class MyStack { /** * 使用LinkedList实现 堆栈 * 堆栈结构特点:先进后出 * 队列结构特点:先进先出 * @author Administrator */ //使用LinkedList实现 堆栈 private LinkedList list =new LinkedList(); /** *@param O */ public void push(Object o) { list.add(o); } /** * * @return */ public Object pop() { Object first =list.getFirst(); list.removeFirst(); return first; } /** * 实现堆栈元素的数量 * @return */ public int size() { return list.size(); } public static void main(String[] args) { MyStack statck =new MyStack(); statck.push("a"); statck.push("b"); statck.push("c"); statck.push("d"); statck.push("e"); while(statck.size()!=0) { System.out.println(statck.pop()); }
2.集合框架Set集合特征(无序和唯一)
public class Demo1 { public static void main(String[] args) { //Set集合 特点:无序,唯一 //(2)无序:元素添加的顺序与输出的顺序不一致 //(3)唯一:不能添加重复元素 //问题:被覆盖?还是过滤? // Set<String> set =new HashSet<>(); // set.add("zs"); // set.add("ls"); // set.add("ww"); // set.add("zs"); Set<Student> set =new HashSet<>(); set.add(new Student(1,"zs","80f")); set.add(new Student(2,"ls","30f")); set.add(new Student(3,"ww","150f")); set.add(new Student(4,"zs","80f")); //1.equals方法。先比较hashcode值,再比较equals //2.1hashcode如果值相同,则不进行比较equals //2.2hashcode值不相同,则不比较equals /* Student stu =new Student(); stu.equals(null); set.forEach(System .out::println); */ //2.遍历(2) //1.foreach for (Student student : set) { System.out.println(student); } System.out.println("--------------------------------"); //iterator //获取迭代器 Iterator<Student>it =set.iterator(); //循环遍历 while(it.hasNext()) { System.out.println(it.next()); } }
3.集合框架Set遍历方式(foreach和迭代器)
public class Demo2 { public static void main(String[] args) { //TreeSet:集合元素按特定规则排序; /* * Set<String> set =new HashSet<>(); set.add("zs"); set.add("ls"); set.add("ww"); */ Set<Student>set =new HashSet<>(); set.add(new Student(1,"zs","80f")); set.add(new Student(2,"ls","30f")); set.add(new Student(3,"ww","150f")); set.forEach(System .out::println); }
4.集合框架TreeSet排序(Comparable和Comparator)
//java.long .Comparable:接口自然比较 //java。utils.Compatator:比较器 Set<Student>set =new TreeSet<>(new NameComparator()); set.add(new Student(1,"zs","80f")); set.add(new Student(2,"ls","30f")); set.add(new Student(3,"ww","150f")); set.forEach(System .out::println);