`
Jeff88
  • 浏览: 4735 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Collections.singletonList设置为不可改变对象

 
阅读更多
package Collections;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;



class People {
	
	private String neme  ;
	
	private int age ;
	
	private List<Integer>  tt ;

	public People() {
		super();
		// TODO Auto-generated constructor stub
	}

	public People(String neme, int age) {
		super();
		this.neme = neme;
		this.age = age;
	}

	
	public List<Integer> getTt() {
		return tt;
	}

	public void setTt(List<Integer> tt) {
		this.tt = tt;
	}

	public String getNeme() {
		return neme;
	}

	public void setNeme(String neme) {
		this.neme = neme;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	
	
	
}


public class SingletonList {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		/*List<People> pLis = new ArrayList<People>() ;
		People pp ;
		for (int i = 0; i < 3; i ++ ) {
			pp = new People() ;
			pp.setNeme("man"+i);
			pp.setAge(20 + i);
			pLis.add(pp) ;
		}
		
		
		
		int[] array = {23,234,212,11};
		pLis = Collections.singletonList(new People("不可变列表,不能再进行改变",27)) ;
		
//		这里如果再对pList进行操作,则会报UnsupportedOperationException
		pLis.add(new People("三", 20));
		
		for (People p : pLis) {
			System.out.println(p.getNeme());
		}*/
		
		
		People pp = new People() ;
		
//		虽然设置的Tt对象是不可变的对象,但是pp对象继续可以设置,看项目中有的同事这样用,感觉怪怪的
		pp.setTt(Collections.singletonList(333));
		
		
		List<Integer> lis = new ArrayList<Integer>() ;
		for (int i = 0; i < 3; i ++) {
			lis.add(new Integer(i));
		}
		
		pp.setTt(lis);
		
		for (Integer ii : pp.getTt()) {
			System.out.println(ii);
		}
		
		
		
	}

}

 

collection工具类中singleton的用法有三个:

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics