आप
beanList = Collections.unmodifiableList(beanList);
कर सकते हैं जब आप beanList
प्रारंभ है यह अपरिवर्तनीय बनाने के लिए -
public void action() {
List<MutableClass> mutableList=Arrays.asList(new MutableClass("san","UK",21),new MutableClass("peter","US",34));
List<MutableClass> immutableList=immutateList(mutableList);
}
public List<MutableClass> immutateList(List<MutableClass> mutableList){
//some code here to make this beanList immutable
//ie. objects and size of beanList should not be change.
//ie. we cant add new object here.
//ie. we cant remove or change existing one.
}
नीचे मेरी MutableClass
है।
तुम दोनों आंतरिक तरीकों कि सूची को संशोधित सक्षम होना चाहिए, और जनता के तरीकों कि संशोधन की अनुमति नहीं होना चाहिए है, तो मैं आपको बस इतना
// public facing method where clients should not be able to modify list
public List<Bean> getImmutableList(int size) {
return Collections.unmodifiableList(getMutableList(size));
}
// private internal method (to be used from main in your case)
private List<Bean> getMutableList(int size) {
List<Bean> beanList = new ArrayList<Bean>();
int i=0;
while(i<size) {
Bean bean = new Bean("name"+i,"address"+i,i+18);
beanList.add(bean);
i++;
}
return beanList;
}
सुझाव देंगे (आपका Bean
वस्तुओं पहले से ही अपरिवर्तनीय लग रहे हैं।)
में एक नोट के रूप में: आप जावा 8 उपयोग करने के लिए होता है, तो अपने getMutableList
निम्न प्रकार से व्यक्त किया जा सकता:
return IntStream.range(0, size)
.mapToObj(i -> new Bean("name" + i, "address" + i, i + 18))
.collect(Collectors.toCollection(ArrayList::new));
तुम वहाँ अपरिवर्तनीय नहीं है क्या है, क्योंकि आप बहुत आसानी से .add (ऑब्जेक्ट ओ) विधि को कॉल कर सकते हैं। ArrayList का उप-वर्ग बनाएं, .add (..) विधि को ओवरराइड करें और इसके पास या तो खाली कार्यान्वयन है, या एक अनचेक अपवाद फेंक दें। और, उस वर्ग के फाइनल बनाने के लिए, ताकि आप इसे उपवर्ग नहीं कर सकते हैं और कार्यान्वयन – Stultuske
बदलते हैं, तो किसी अन्य वस्तु में सूची लपेटें सकता है और केवल लागू अपने प्रश्न का Iterable इंटरफ़ेस –
उत्तर: http://stackoverflow.com/questions/10750791/क्या-है-भावना के- अंतिम ArrayList –