JAVA set, set a common method

Set
set of relatively similar array itself is a reference type, you can store many types,
except that the length of the array can not be changed, change the length may be arbitrarily set.
There are many set contains: ArrayList, HashSet, LinkedList, HashMap ...
the easiest ArrayList can be similar to other collections.

ArrayList generic class (a data type unification)

  • java.util.ArrayList is a class, there are three steps to use.

  • 1.导包
    import java.util.ArrayList

  • 2. Create a
    class name of the object name = new class name ();
    ArrayList common constructor:
    ArrayList <generic> list = new ArrayList <> ( );
    generic: the collection is stored in the unity of all what type of data.
    Note: Generics can only be a reference type, not a basic type

  • 3. Use

public class ArrayList {
	public static void main(String[] args) {
		// 创建一个集合,存放的全都是String字符串类型的数据
		ArrayList<String> list1 = new ArrayList<>();
		
		//泛型只能写引用类型,不能写基本类型,下面是错误写法!
//		ArrayList<int> list = new ArrayList<>();
	}
}

Common methods for the collection

  • 1. Adding an element
    public boolean add (E element): adding an element to the set, the parameter is an element to be added, successful returns true representatives

  • 2. Get element
    public E get (int index): Gets an element from among a set of parameters is an element index (starting from 0), the return value is acquired element object obtained

  • 3. Get length
    public int size (): Get the number of elements of the collection, set the length, obtain a digital int

Note:
ArrayList object is a collection of direct printing name, not the address value obtained, but similar content, format and arrays.
ArrayList toString method because this class has special handling.

For ArrayList collection, the addition of add certain action is successful, the return value must be true.
But for others it is a collection, add method is not necessarily successful.

public class ArrayListMethod {
	public static void main(String[] args) {
		ArrayList<String> list = new ArrayList<>();
		
		System.out.println(list); //[]
		
		//向集合中添加元素add
		list.add("A");
		list.add("B");
		list.add("C");
		System.out.println(list); //[A,B,C]
		
		boolean success = list.add("D");
		System.out.println("添加元素是否成功:"+success);//true
		System.out.println(list); //[A,B,C,D]
		
		String name = list.get(1);//获取第一号元素
		System.out.println(name);  //B
		//获取只是拿到,不会从原集合中删除
		System.out.println(list);  //[A,B,C,D]
		
		System.out.println("集合的长度"+list.size()); //4
		list.add("1");
		list.add("4");
		list.add("7");
		System.out.println("集合的长度"+list.size()); //7
		
	}
}
Published 52 original articles · won praise 6 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_43472877/article/details/104103699