Java集合之List、set和map的常用方法

ArrayList

ArrayList 的常用方法 。

  • .add();
  • .remove(); //可以是index和Object类型。Object移除第一次出现的指定元素。
  • .indexOf(“ab”);
  • .lastIndexOf(“a”);
  • .size();
  • .get(index);
  • .set(index,obj); //修改集合的数值
  • .contains(Object o) //list是否包含对象o;
  • .clear //移除所有元素;
class ListExample {



   public static void main(String[] args){

         ArrayList list = new ArrayList();

         list.add("aaa");

         list.add("ccc");

         list.add(2,"ccc");

         for (int i=0;i<list.size();i++) {

             String obj =(String) list.get(i); 

             System.out.println(obj);



         }

         list.set(1,"bbb");      //集合的修改。

list.remove(2);   //通过索引删除集合的值。list.remove("ccc") 通过值删除

         System.out.println(); 

         for (Object obj:list){

             System.out.println(obj);

         }

         aaa

         ccc

         ccc



         aaa

         bbb

 

LinkedList

                 LikedList常用方法

.addFirst(Object o) 在列表首部添加元素

.addLast(Object o) 在列表的末尾添加元素

.getFirst() 返回列表中的第一个元素

.getLast() 返回Object;

.removeFirst() 返回Object;

.removeLast() 返回Object;

.size();

 


        

LinkedList list = new LinkedList();

         list.addFirst("aaa");

         list.add("bbb");

         list.add("ccc");

         list.addLast("ddd");

         for (int i=0;i<list.size();i++) {

             String obj =(String) list.get(i); 

             System.out.println(obj);



         }

         list.set(1,"eee");      //替换指定索引下的元素

         list.remove(2);   //通过索引删除集合的值

         System.out.println(); 

         for (Object obj:list){

             System.out.println(obj);

         }

         System.out.println(list.size());

         System.out.println(list.getLast());

         System.out.println(list.getFirst());

  

         aaa

         bbb

         ccc

         ddd



         aaa

         eee

         ddd

         3

         ddd

         aaa

   }

  

 }

 

Set接口

  • Set接口存储一组唯一,无序的对象
  • HashSet是Set接口常用的实现类
  • Set中存放对象的引用

 

TreeSet

class Cat implements Comparable<Cat>{

    public String name;

    public int age;



   



      public Cat(String name,int age) {



      this.name =name;

      this.age=age;

      }







      @Override

      public String toString() {

           return "Cat [name=" + name + ", age=" + 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;

      }







      @Override

      public int compareTo(Cat o) {

           // TODO Auto-generated method stub

           return this.age-o.age;

      }   

}

public class CatTreeSet {

    public static void main(String[] args) {

       TreeSet<Cat> treeSet = new TreeSet<Cat>();

        for (int i = 0; i < 10; i++) {

        Cat cat = new Cat("name"+i,i);

        treeSet.add(cat);

        }

       

       

        System.out.println("------------TreeSet并保证迭代顺序----------------");

        System.out.println("forEach遍历");

        showForEach(treeSet);

       

       

        System.out.println("------------TreeSet并保证迭代顺序----------------");

        System.out.println("迭代器遍历");

        showIterator(treeSet);

    }

    private static void showIterator(TreeSet<Cat> treeSet){

        Iterator<Cat> iterator = treeSet.iterator();

        while (iterator.hasNext()){

        Cat cat = iterator.next();

            System.out.println(cat);

        }

    }

    private static void showForEach(TreeSet<Cat> treeSet) {

        for (Cat cat :treeSet){

            System.out.println(cat);

        }

    }

     

}

 

 

 

 

 

HashSet

  • 实现了Set接口,保证元素的唯一性即不允许重复.
  • 从下面源码可以看到底层基于HashMap
  • HashSet源码(JDK1.8)
  • 只能迭代获取元素,没有get等方法


    

  public HashSet() {

        map = new HashMap<>();

    }

    public HashSet(int initialCapacity, float loadFactor) {

        map = new HashMap<>(initialCapacity, loadFactor);

    }

    public HashSet(int initialCapacity) {

        map = new HashMap<>(initialCapacity);

    }





    public Iterator<E> iterator() {

        return map.keySet().iterator();

    }

    public int size() {

        return map.size();

    }

    public boolean isEmpty() {

        return map.isEmpty();

    }

    public boolean contains(Object o) {

        return map.containsKey(o);

    }

    public boolean add(E e) {

        return map.put(e, PRESENT)==null;

    }

    public void clear() {

        map.clear();

}





class Cat{

    private String name;

    private String type;



    public String getName() {

        return name;

    }



    public void setName(String name) {

        this.name = name;

    }



    public String getType() {

        return type;

    }



    public void setType(String type) {

        this.type = type;

    }



    public Cat() {



    }



    public Cat(String name, String type) {

        super();

        this.name = name;

        this.type = type;

    }



    public String toString() {

        return "Cat [name=" + name + ", type=" + type + "]";

    }



}

public class CatHashSet {

    public static void main(String[] args) {

        HashSet<Cat> hashSet = new HashSet<Cat>();

        for (int i = 0; i < 10; i++) {

        Cat cat = new Cat("name"+i,"cat"+i);

            hashSet.add(cat);

        }

       

       

        System.out.println("------------HashSet并不保证迭代顺序----------------");

        System.out.println("forEach遍历");

        showForEach(hashSet);

       

       

        System.out.println("------------HashSet并不保证迭代顺序----------------");

        System.out.println("迭代器遍历");

        showIterator(hashSet);

    }

    private static void showIterator(HashSet<Cat> hashSet){

        Iterator<Cat> iterator = hashSet.iterator();

        while (iterator.hasNext()){

        Cat cat = iterator.next();

            System.out.println(cat);

        }

    }

    private static void showForEach(HashSet<Cat> hashSet) {

        for (Cat cat :hashSet){

            System.out.println(cat);

        }

    }

}



 

 

Map

HashMap常用方法

  • put(key,value);   //添加、修改。
  • -size();          //返回元素的个数
  • -get(key);        //根据键返回相关联的值,如果不存在指定的键,返回null
  • -keySet()         //返回键的Set集合
  • entrySet()        //返回键值对的Set集合
  • 不能由get()方法来判断Map中是否存在某个键,而应该用containsKey()方法来判断
  • Hashtable的使用不被推荐,因为HashMap提供了所有类似的功能,并且速度更快。当你需要在多线程环境下使用时,HashMap也可以转换为同步的。

import java.util.Collection;

import java.util.HashMap;

import java.util.Map;



public class MapDemo {



      public static void main(String[] args) {



           // 键是String,值是Integer

           Map<String, Integer> map = new HashMap<>();

           //可以添加多个null但是只能存储一个null类型,不管是key、value还是key-value

           map.put(null, null);

           map.put(null, null);



           // 添加元素

           map.put("a", 5);

           map.put("t", 7);

           map.put("f", 5);

           map.put("e", 3);

           map.put("o", 8);

           map.put("h", 0);

           // 如果键重复,则对应的值覆盖

           map.put("h", 9);



           // 将映射中所有的值放入一个集合中返回

           Collection<Integer> values = map.values();

           System.out.println(values);

           // 获取键值对个数

           System.out.println(map.size());



           // 清空映射

           //map.clear();



           // 删除键值对

           map.remove("e");



           // 判断是否包含指定的键

           System.out.println(map.containsKey("s"));

           // 判断是否包含指定的值

           System.out.println(map.containsValue(0));



           // 获取指定的键所对应的值

           System.out.println(map.get("f"));

            // 如果对应的键值对不存在,则返回null

           System.out.println(map.get("p"));



           System.out.println(map);

           8

[null, 5, 7, 3, 5, 9, 8]

7

false

false

5

null

{null=null, a=5, t=7, f=5, h=9, o=8}

--------------迭代遍历Map集合的两种方法--------------

--------------方式一:获取所有的键key进行遍历--------------

null

a

t

f

h

o

--------------方式一:获取所有的键值对key-value进行遍历--------------

null null

a 5

t 7

f 5

h 9

o 8 }



}

Iterator 迭代器

.hasNext();     //返回 boolean,如果仍有元素可以迭代,则返回true。 

.next();        //E 返回迭代的下一个元素。 

.remove();      //从迭代器指向的collection中移除迭代器返回的最最后一个元素。

 

引申: https://blog.csdn.net/xczheng/article/details/3936474.

 

猜你喜欢

转载自blog.csdn.net/qq_40531768/article/details/89356983