यदि उपलब्ध हो तो मैं एक मौजूदा संग्रह कास्ट करने के लिए अपनी कस्टम उपयोगिता का उपयोग करता हूं।
मुख्य:
public static <T> Collection<T> toCollection(Iterable<T> iterable) {
if (iterable instanceof Collection) {
return (Collection<T>) iterable;
} else {
return Lists.newArrayList(iterable);
}
}
आदर्श रूप से उपरोक्त ImmutableList का उपयोग करेगा, लेकिन ImmutableCollection nulls को अनुमति नहीं देता है जो अवांछनीय परिणाम प्रदान कर सकता है।
टेस्ट:
@Test
public void testToCollectionAlreadyCollection() {
ArrayList<String> list = Lists.newArrayList(FIRST, MIDDLE, LAST);
assertSame("no need to change, just cast", list, toCollection(list));
}
@Test
public void testIterableToCollection() {
final ArrayList<String> expected = Lists.newArrayList(FIRST, null, MIDDLE, LAST);
Collection<String> collection = toCollection(new Iterable<String>() {
@Override
public Iterator<String> iterator() {
return expected.iterator();
}
});
assertNotSame("a new list must have been created", expected, collection);
assertTrue(expected + " != " + collection, CollectionUtils.isEqualCollection(expected, collection));
}
मैं संग्रह (सेट, सूची, आदि) के सभी उपप्रकारों के लिए समान उपयोगिताओं को लागू करता हूं। मुझे लगता है कि ये पहले से ही अमरूद का हिस्सा होंगे, लेकिन मुझे यह नहीं मिला।