当前位置:网站首页>What is generics and the use of generics in collections [easy to understand]

What is generics and the use of generics in collections [easy to understand]

2022-06-25 18:05:00 Full stack programmer webmaster

Hello everyone , I meet you again , I'm your friend, Quan Jun .

What is generics ?

Generics are most commonly used with collections , Because generics were first added Java It is to solve the problem of set downward transformation . If we have such a need : Define a description circle , The data type in the circle is required to be indeterminate , That is, when the name attribute is used , Attribute types are indeterminate . For example, describe that there is a radius in a quasi circle , The required radius can be int, It can also be used. double. Then the data type is uncertain , Just use generics , Parameterize data types .

Use of generics in collections

List Use generics

When we create a collection, we use <> To declare List Collections can only be saved Dog Class object List dogs=new ArrayList<>(); establish Dog Class object Dog dog1 = new Dog(“101”,“ Laifu ”); add to Dog Object to collection dogs.add(dog1);// here dogs Only... Can be stored in the collection Dog Class object

public class ListTest { 
   

	public static void main(String[] args) { 
   
		// Statement List Collections can only be saved Dog Class object 
		List<Dog> dogs=new ArrayList<>();
	 
		// establish Dog object .
		Dog dog1=new Dog();
		dog1.setId(111);
		dog1.setName(" Laifu ");
		
		Dog dog2=new Dog();
		dog2.setId(112);
		dog2.setName(" Laifu 2");
		
		//Dog Objects adding to collection 
		dogs.add(dog1);
		dogs.add(dog2);
		
		// Get an element 
		Dog dog = dogs.get(1);
		System.out.println(dog);
		
		// get List Iterators of sets 
		Iterator<Dog> it = dogs.iterator();
		while(it.hasNext()) { 
   
			Dog next = it.next();
			System.out.println(next);
		}
		
		// Use advanced for Traversal 
		for(Dog d:dogs) { 
   
			
			System.out.println("--"+d);
		}
		
	}
}

Map Use generics

Create a collection object ,key by String type ,value by Dog Class types . Map<String,Dog> dogs=new HashMap<>(); take dog Object to save to Map Collection dogs.put(“111”, dog1);// At this time key Only string type ,value Can only be Dog type

summary :

The purpose of using generics in collections is to solve the problem of downward transformation , After the generic materialization , Collections can only store types that are materialized with generics .

Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/151141.html Link to the original text :https://javaforall.cn

原网站

版权声明
本文为[Full stack programmer webmaster]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206251753412512.html