collection 1 « collection « Java Collection Q&A

Java Collection Q&A
3.Array Byte
4.Array Char
5.Array Convert
6.Array Dimension
7.Array Integer
8.Array Object
9.Array String
14.Garbage Collection
Java Collection Q&A » collection » collection 1 

1. Java Collections using wildcard

public static void main(String[] args) {

 List<? extends Object> mylist = new ArrayList<Object>();

 mylist.add("Java"); // compile error

The above code (obviously) does not allow you to add elements to the list and ...

2. Rule of thumb for choosing an implementation of a Java Collection?

Anyone have a good rule of thumb for choosing between different implementations of Java Collection interfaces like List, Map, or Set? For example, generally why or in what cases would I prefer ...

3. Using Small (1-10 Items) Instance-Level Collections in Java

While creating classes in Java I often find myself creating instance-level collections that I know ahead of time will be very small - less than 10 items in the collection. But ...

4. Classical set operations for java.util.Collection

Is there any built-in functionality for classical set operations on the java.util.Collection class? My specific implementation would be for ArrayList, but this sounds like something that should apply for all subclasses ...

5. Is there a type-safe Java implementation of 'reduce'?

I often need to run reduce (also called foldl / foldr, depending on your contexts) in java to aggregate elements of an Itterable. Reduce takes a collection/iterable/etc, a function of ...

6. Genericized commons collection

I'm astonished that the Apache Commons Collections project still hasn't got around to making their library generics-aware. I really like the features provided by this library, but the lack ...

7. Monitor changes to a collection

Say you have the following java bean:

public class MyBean
    private List<String> names = new ArrayList<String>();

    public void addName(String name)

8. TreeViolationException problem

Hi Im having some trouble when inserting to the right of a node in a binary tree... I just dont see why the exception is happening. This is the method ...

9. when to use Set vs. Collection?

Is there any practical difference between a Set and Collection in Java, besides the fact that a Collection can include the same element twice? They have the same methods. (For example, does ...

10. How do you associate each Collection's item to another one's?

I have two Collection objects, I want to associate each object of these two in a readable way (HashMap, Object created on purpose, you choose). I was thinking of two loops one ...

11. Java collections brain teasers

Java collections are invaluable tool in exchanging data between database and service layer. We have various cases of a HashMap, ArrayList, a HashMap of arraylists etc. I'm looking for programming samples, that ...

12. Java random collection

Is there a kind of Java collection that the order of my fetching is random? For example, I put integer 1, 2, 3 into the collection and when I try to ...

13. What is the exact difference between these two groups of statements?

Set<Type> union = new HashSet<Type>(s1);
Set<Type> union = new HashSet<Type>();
Set<Type> s1 = new HashSet<Type>();

14. What does this statement mean?

I am a beginner in Java and do not understand what if(!s.add(a)) means in this code excerpt:

Set<String> s = new HashSet<String>();
for(String a:args) {
    if(!s.add(a)) System.out.println("Duplicate detected:"+a);

15. Is there any difference between these two groups of statements

Set<Type> union = new HashSet<Type>(s1);
Set <Type> union = new HashSet<Type>();

16. How do I model multi-variable function?

We know that Map interface models function abstraction in math. How should I model multi-variable function? For example, to model f(x, y, z), I have two options:

Map<List<Integer>, Integer> f1;
Map<Integer, Map<Integer, ...

17. Java - Collection Selection

What generics collection class can I use that provides both mapping and array-like functionality. For example, I want to map a String to a Double and I want to reference the ...

18. When should I use Iterable vs. Collection in Java?

What are the considerations of using Iterable<T> vs. Collection<T> in Java? For example, consider implementing a type that is primarily concerned with containing a collection of Foos, and some associated metadata. The ...

19. Is there a bounded non-blocking Collection in Java?

The only one I can find is the BoundedFIFOBuffer, which is deprecated. Any others?

20. How to most elegantly iterate through parallel collections?

Say I have 2 parallel collections, eg: a list of people's names in a List<String> and a list of their age in a List<Int> in the same order (so that any ...

21. Search/Queries in Collections (Java)

I've created many Geodata objects (name,postalCode,lat,lon). Now I want to put them into a collection to search for different entries later. Everything should happen objectOriented/in-memory, so there shouln't be a need ...

22. Pre Java 5 collections and the unwillingness to change

We have several areas where code like this can be seen

public Map extractData(ResultSet rs) throws SQLException, DataAccessException {
     Map m = new HashMap();

23. Java: Get first item from a collection

If I have a collection, such as Collection<String> strs, how can I get the first item out? I could just call an Iterator, take its first next(), then throw the Iterator ...

24. How to iterate through a Collection>

I have something like this:

something need here  = scope.getConnections();

//getConnections() returns Collection<Set<IConnection>>
I need to iterate through all connections (the stuff that the getConnections() returns) How to do that ?

25. A collection that represents a concatenation of two collections in Java

Is there a class that represents the concatenation of a collection with another collection? This class should be a Collection in itself, and should delegate all methods to the underlying (inner) ...

26. customising serialisation of java collections using xstream

I have an object that needs to be serialised as XML, which contains the following field:

List<String> tags = new List<String>();
XStream serialises it just fine (after some aliases) like this:

27. Difference between Java Collection and Collections

I just want to know what the actual difference between Java Collection and Collections is. Thanks in advance!

28. java function - print(collection c)?

I'm trying to learn java better and I got one question. Say I got two collections, an ArrayList and a LinkedHashSet. Is it possible to make a function like this:

void print(collection c) ...

29. Duplicate values in the Set collection?

Is it possible to allow duplicate values in the Set collection? Is there any way to make the elements unique and have some copies of them? Is there any functions for Set collection ...

30. Language Tricks to Shorten My Java Code?

I am currently rediscovering Java (working with Ruby a lot recently), and I love the compilation-time checking of everything. It makes refactoring so easy. However, I miss playing fast-and-loose with types ...

31. java: returning a collection

What's the best way to return a collection in Java? Should I allow the caller to provide a collection to add to? Or just return a List<> or Set<> of items? Or ...

32. java - how to flatten a collection of sets, and should I do it in the first place?

say i have a graph, implemented with two maps (in and out) that map (source, set(edge)) and (target, set(edge)), respectively. until now, i also had allEdges set, which i decided to ...

33. Prefix matching/trie for Java?

I'm porting over a C program to Java. I need to do prefix lookups. e.g. given the keys "47" , "4741", "4742 a input of "474578" should yield the value for "47" ...

34. having problem adding to a collection

I am adding information about different books, cd, dvd from main() I am trying to use inheritance in this project... First, i am a beginner so keep that in mind when you help ...

35. find a keyword in a collection and return it

I have a collection i added CD, DVD, book information into hashsets. Each one has a keyword and i would like to do a search for a specific keyword and return the ...

36. What structure would you recommend to use to hold a bunch of String-Object associations?

it'll be used to key-map String-Object value. let's say, myObject = struct.get("first"); ordering is not important. parameterized Hashset or anything better? if that doesn't bother you, can you give me an example of static ...

37. Java collection reference-copy

Is there a standard Java (1.5+) implementation (i.e. no 3rd party) of a collection which allows me to glue several collections into one? Here's a sketch, of how it works:

final SomeCollection x ...

38. Bounded PriorityBlockingQueue

PriorityBlockingQueue is unbounded, but I need to bound it somehow. What is the best way to achieve that? For information, the bounded PriorityBlockingQueue will be used in a ThreadPoolExecutor. NB: By bounded I ...

39. What's the preferred way to assign a collection from a parameter?

I have this class:

public MyClass {
    public void initialize(Collection<String> data) { = data; // <-- Bad!

40. Java collections that spool to disk

I'm running out of memory in Java due to some very large Lists and Sets built up over the course of a transaction and iterated over just once at transaction's end. ...

41. Storing primitive values in a Java collection?

Java collections only store Objects, not primitive types; however we can store the wrapper classes. Why this constraint?

42. Interpolating Large Datasets On the Fly

Interpolating Large Datasets I have a large data set of about 0.5million records representing the exchange rate between the USD / GBP over the course of a given day. I have an ...

43. Is there something like find_if in Java?

In C++, I can use find_if with a predicate to find an element in a container. Is there something like that in Java? The contains method on collections uses equals and ...

44. Why collection literals?

Hi fellow Java programmers. From the various online articles on Java 7 I have come to know that Java 7 will be having collection literals like the following:

List<String> fruits = [ "Apple", ...

45. Java Collection which pages to disk when it gets full?

A colleague mentioned that he heard about a lightweight collection which would automatically page out to disk when it's contents got too full - but he couldn't remember the name. I ...

46. Why are AbstractQueue and AbstractList disjointed?

During my C learning days, when I had implemented a Queue, I implemented them on top of a LinkedList. So essentially I had two pointers (front and rear) for the Queue ...

47. How to pop items from a collection in Java?

Is there a method in JDK or apache commons to "pop" a list of elements from a java.util.List? I mean, remove the list of elements and return it, like this method:

public ...

48. Java Double entry table

Does anyone know a double entry table implementation in java I can download ? I need to do something like this

   1  2  3
a| ...

49. Two way collections in Java

I have a list of objects. The objects are given an ID and stored in a Hashtable. If I need an object with particular ID, I simply say:

However, sometimes I need ...

50. Advanced Collections in Java?

To Understand the Collection Package Properly. The new API's which are to do the more advantage and comfortable of using Collections. for Example ConcurrentHashMap can able to load the data to ...

51. Java primitive collections library

What is the best Java primitive collections library? (most memory and time efficient) I've found Trove and FastUtil to be the most used ones, but haven't found much comparison between them ...

52. Need Help And Ideas In Solving A Collection Problem

I have already posted a question today. This question is about the same project but unrelated. I am developing an application for the Lego NXT Mindstorm robot. I have two ...

53. AI Implementation for a Card Game

How can I implement a collection of three computer opponents in a client/server Java game? Thanks...

54. What is static ?

I am just reading through collection java tutorial and wondering why the <E> is needed after static?

public static<E> Set<E> removeDups(Collection<E> c) {
    return new LinkedHashSet(c);

Thanks, Sarah

55. Collection as a metaphor for real world containers

I find modeling physical containers using collections very intuitive. I override/delegate add methods with added capacity constraints based on physical attributes such as volume of added elements, sort based on physical ...

56. How to specify xml documents to transform with resource collection in ant?

I'm trying to use ant to use XSLT to preprocess three specific stylesheets in my project. The Ant documentation for the xslt task says that it should be able ...

57. Are there any good libraries of functions to use with collections in Java, such as

Are there any good libraries of functions to use with collections in Java. I'm thinking along the lines of implementations of partition, take, drop, takeWhile, dropWhile, map, filter, reduce...? ...

58. What is a java collection?

I want to know: What is a collection in Java?

59. java collection

give me a simple trick to understand java collection properly.. you can give a website address also..

60. Why PriorityQueue in Java cannot have initialCapacity 0?

I use PriorityQueue for partial sorting of some data. In particular, this is the code:

Collection<Data> data = ...;
PriorityQueue<Data> queue = new PriorityQueue<Data>(data.size(), dataComparator);
// iterate over queue with remove() until we have ...

61. Where to find an overview of backed Collection methods/classes

I am trying to find an overview of all methods in the java.util package returning backed Collections (and Maps). The only ones easy to find are the synchronizedXX and immutableXX. But ...

62. Space invaders game

I am writing a space invaders game I need to write 5 public instance variables which hold collections recording all of the information about one run of the game: spaceShips will reference ...

63. Collection for ThreadIds

I am looking for a thread-safe collection of to store ThreadIDs (long) in Java. What is the best option? I need to preserve the order of addition.

64. compact syntax for instantiating an initializing collection

I'm looking for a compact syntax for instantiating a collection and adding a few items to it. I currently use this syntax:

Collection<String> collection = new ArrayList<String>(Arrays.asList(new String[] { "1", "2", "3" ...

65. What Java Collections library do you recommend?

I've inherited a team and a (Java) code base. The code base makes use of a lot of explicit for each loops. I'd like to replace those (edit: in future code) with ...

66. Java Collections Logic / Over coding issue

Below is an implementation of an exercise I've been asked to do (see comments). It works, and the reason I'm posting it is that the function checkMiracle looks like it should ...

67. Which collection to use in Java?

I want to map integers to strings, they are one-to-one such as :

60 : c
61 : c#
62 : d
63 : d#
64 : e
65 : f
66 : f#
But I need to have ...

68. Why does exist WeakHashMap, but absent WeakSet?

From J. Bloch

A ... source of memory leaks is listeners ... The best way to ensure that callbacks are garbage collected promptly is ...

69. Easy access to entries in set - using where conditions

The class structure is of the following format-

class A
   Set<B> bHolder;

class B
   Set<C> cHolder;

class C
   String data;
Goal : To retrieve an entry from class A ...

70. doubly-linked list

Hi I want to know that how can I copy my objects from an arrayList to a doubly linked list? also my DNode constructor is :

    public DNode(Object element, DNode ...

71. Collection in Java

Quick Question... Can collections in Java hold more than one type? Or do they all have to be the same type? thanks

72. collections in java

So I have this code. Basically it should be able to take a stock of any type, and you should be able to buy from this stock into a collection ...

73. Java Collections: which collection to use and when?

As we all know with Java comes the Collections API that provide us with numerous data structures that we can use. I was wondering if there is some ...

74. Canonical toList in java?

Is there something like this in any standard library (e.g. apache-commons, guava) ?

public static <T> List<T> toList(Iterable<T> iterable) {
    if (iterable instanceof List)

75. Why can't I set a Transformer to a LazyList in Apache Commons?

In apache.commons.collections there is a class called MapUtils which have these two methods to define a Map which can create on demand objects for the map:

76. Why aren't Collections.checkedMap and friends used more commonly?

I recently stumbled across the Javadoc for the Collection.checkedMap family of functions for creating dynamically typesafe views of the standard Collections types. Considering that they add another layer of safety ...

77. removeAll seems to affect its argument

I have written a generic Partition class (a partition is a division of a set into disjoint subsets, called parts). Internally this is a Map<T,Integer> and a Map<Integer,Set<T>>, where the Integers ...

78. Complexity of processing a collection's values

I need to store a growing large number of objects in a collection. While performing actions of each object of the collection, I regularly need to check whether an object is ...

79. java.util.Collection with the lowest overhead?

I'm calling a method in another API that accepts a java.util.Collection of objects. I've looked at the method and it immediately copies everything in the collection into a new ArrayList before ...

80. What collection should I choose?

I need just a collection of two pairs of data, none of them is going to be null. I don't need any sorting or other possibilities. What implementation of Map should ...

81. Good collection for keeping track of characters

Just a general question (and I'm sort of new to java) but what would be a good collection that I could add objects to, and keep track of how many of ...

82. member of a collection?

I have two classes, Foo and Bar. Each Foo has a name and a bunch of items. Bar contains a bunch of Foo's, each with a unique name. Bar has a ...

83. What collection to use here

I'm wondering what collection I should use for this purpose: Requirements

  1. Must contain tuples <value1,value2>
  2. There is not relation between those values (no key-value pairs)
  3. Can only contain unique tuples
  4. <value1,value2> is equal to <value2,value1>
What would ...

84. Java join collections using functor

2 collections are given with the same number of elements, say List<String>. What are elegant ways in JAVA to apply a functor on each 2 elements of collections with corresponding indexes? Say, ...

85. Adding collections to one another

I'm reviewing for a class, and this is an old question: I need to write a method

void addAll(Collection c1, Collection c2);
that adds all the elements in c2 to c1. Could I just do ...

86. Defining Collections in drl file

i'm going to do some ruling stuff with drools. This is the first time i use this tool and, for functional requirements, i've thought a need to define a weights data-structure in ...

87. Check for value in collection

I'm trying to check a collection for a particular value i.e. I want to check the collection of players for a positionType = attacker. It does not matter how man references, as ...

88. Wrapping multiple Iterables into a single Interable

Say I have two Collections:

Collection< Integer > foo = new ArrayList< Integer >();
Collection< Integer > bar = new ArrayList< Integer >();
and say sometimes I would like to iterate over them individually, ...

89. Java Collections & aliasing

How do you deal with aliasing in Java? A simple solution is to make a copy of let's say an ArrayList but when i try to write the code my data ...

90. Java LinkedBlockingQueue Realization

I looked at JDK LinkedBlockingQueue class and was lost.

public void put(E e) throws InterruptedException {
    if (e == null) throw new NullPointerException();
    // Note: convention ...

91. What is a WeakHashMap and when to use it?

What is a WeakHashMap and when should one be using it? What are the differences between a WeakHashMap and a HashMap?

92. Collection in jasper reports

I have a list of objects and I want to print them in a jasper pdf output as a table. The objects have 3 String istances. So I want something like ...

93. Collections.emptyList() vs. new instance

In practice, is it better to return an empty list like this:

public class Configuration
    private List<Foo> fooList;

    // do stuff

94. Does java provide capped collection

For example, a capped list which automatically delete the first inserted items if the total items pass the specified amount? Any builtin or 3rd party support?

95. How to hold collection of files throughout application?

In my mobile application I need to hold a collection of File objects (pictures, documents) that can be accessed throughout the whole application and users can make various operations over the ...

96. How to declare cluster in java?

I need to create clusters that contain elements. The clusters should be created at run-time and elements to be added to it. How do I do it in Java? I thought of ...

97. Call addFirst on a Collection

Collection col = new LinkedList();
Is there a way to call col.addFirst ?

98. Java Collections

I need a tutorial about collections in java expect the Java document, can anyone give some resources about it?

99. Caching set-like collection

I'm trying to cache a lot of similar values with only set-like requirements. Unfortunately Set<?> allows me only to check whether an element exists inside - it won't give the existing ...

100. What's the best practice for returning an internal collection in Java?

I'm curious what is considered a better practice when returning a collection of objects from a mutable class:

public class Someclass {

  public List<String> strings;  

  public add(String in){ ...  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.