collection 4 « 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 4 

1. Collection

an interface is a contract - nothing more, nothing less. Someone has defined a 'Collections' contract. If you choose to write a class that "implements Collection", you MUST provide an implementation for each and every method listed in the class. However, this contract explicitly states that you may not want to implement all the methods - some may not make sense ...

2. Set Collection

Check the Javadoc page of java.util.Set. You're right, it doesn't specify any new methods. It does refine the contract for several methods; for instance, Collection.add specifies that the return value is true if the collection changed. Set.add specified that the return value is true if the element wasn't in the Set already. In other words, by implementing Set you specify that ...

3. Serching for a surname in my collection

Hi, this is my first post so I would first like to introduce myself. My name is Spangle1187 and I am studying a module called Writing Software which is based on OO and Java. I am working on a project to create a address book. So for I have created a contact class to hold the relevant data: public class Contact ...

4. Which Collection to choose?

5. Collection in java

Hi, data in the file(will be read into a Set) (I am not exactly sure as to which collection to be used for this purpose) Please suggest the collection to be used. abc def ghi abc ghi def ghi abc uvw xyz xyz abc xyz def Set contains abc def ghi uvw xyz Each Set must be compared with all the ...

6. Which java Collections Shall i Use?

7. Date ranges in collections

I have a use case where I want to store date ranges in a collection (an object with a start and end date) and find the relevant one that covers a passed in date. I can obviously do this by having a method on the DateRange object to determine if the passed in date falls in this range and iterate through ...

8. Java collections

Just to throw some water on this: At JavaRanch we encourage people to ShowSomeEffort: rather than just asking a flat-out "what should I do" we'd rather see things like "I looked at the various collections, but wasn't sure which one would allow storing two values in each entry." My response would have been "None of them; all collections store a reference ...

9. Help Needed on collections

10. Regarding Collection

@Peter: If the numbers were retrieved randomly, odds are it isn't a stack or queue. @Venu: It depends on how you're retrieving them: if you're removing them as you retrieve them, it's easy. Otherwise you'd need to keep track of which numbers you've retrieved, like by removing them from a map, or using a bitmap, or toggling a flag, or... etc. ...

11. simple Programee on collection

suppose i have sorted list which has integers then write a program that any of 2 integer sum is equal to x(which we give input)? Ex: i have 1,2,3,4,5 in list i have gave x as 9 then i need to write a program that the number 9 i s equal to any of the integers.Her in that case(4+5=9) so i ...

13. ThreadSafe Collection

The lists that Collections.unmodifiableList() and Collections.singletonList() return are two completely different things. unmodifiableList returns a wrapper around the original list that you put in, which provides a read-only view on the underlying list. singletonList creates a new, read-only list with a single element in it. The obvious difference is that singletonList returns a list with only one element in it. The ...

14. Collections in Java

15. Collections

Hi, I had a question about collections. We have Set, List, Map which are interfaces and HashSet, ArrayList, HashMap,... which are the classes that are implement this interfaces. What about the Collection? I had the impression that was an interface but I found it to be a class. What is a class or interface? Thanks

16. Collections

Welcome to JavaRanch! The Collection classes don't allow primitives so they can enforce type safety. This works into the idea of generics, which you may not have studied yet, but you'll see when you get there. Basically, if I tell my Collection I only want to store Integers in it, but then I try to store a Float, or a Boolean, ...

17. Collections Question

I know the below concepts,BUT i want to know some REAL TIME EXAMPLES for the below where they can be used. a>ArrayList -- Unsynchronized Data Structure b>Linked List is based on Doubly linked List Data Structure c>Vector -- Synchronized Data Structure d>HashMap -- Unsynchronized Data Structure e>HashTable -- Synchronized Data Structure f>Queue -- Based on Dequeue Data Structure I wanted some ...

18. Ideal Collection implementation to be used for counting the occurance of a word in a file.

Hello, I was asked the following question during the phase of an interview. There is a text file which stores different words. I need to find the first three words with the most number of occurrences. I first thought that I would use a map with each word as the key and the number of occurrences as the value. If any ...

19. How to get Collection by value?

Thanks a lot for reply... actually, x is my original object & y is similar object, I am carrying choices of user request and as per user choice updating data in y, but at any level user can undo all/any of his choices & in that case I need original data. Then further user can update his choice & undo the ...

21. Collections

Thanks, I thought of this but I do not know how many units and subsunits are coming. I do not know how to name the collections dynamically and then populate them. I tried naming the collections with the unit name in the for loop but I didn't quite get how to do it. Thanks, Vasu

22. Java Collection Questions

When someone asks you to explain your question more clearly, that doesn't mean to just copy what you said before. On the contrary, it asks you to post something different. Something more understandable. Your question was impossible to understand the first time, and repeating it didn't make it any easier to understand. I would suggest for a start posting meaningful code. ...

23. collections help

try{ stmt = con.createStatement(); rs = stmt.executeQuery("select * from appointments"); while({ id = rs.getString(1); date = rs.getString(2); time = rs.getString(3); mgmt_id = rs.getString(4); client_id = rs.getString(6); concat = date+"\t"+time+"\t"+mgmt_id+"\t"+client_id; hm.put(id, concat); Iterator i = hm.keySet().iterator(); while(i.hasNext()) { key =; } System.out.println(hm.get(id)); System.out.println(); } }catch(Exception e){ System.out.println(e); } this is my code....with this code im able to get all the 10records ...

24. Collections Abstraction.

25. Collections

1. compareTo() takes just one argument. If your class implements Comparable, i.e. you can only compare two of your same objects with one type of comparision logic. 2. Collects provides a mechanish for sorting by using Comparator interface. This can be used in conjuction to create any no. of comparision logic, with any type of objects either in desc and asc ...

26. Help me understand Collection polymorphism

Thanks for clearing that up. I had to think about it for a little bit, but I guess the whole point is to choose the variable type that fits your needs and provides the most flexibility based on those needs. It would be bad if I were to have a big program that casts List references to an arraylist, because I ...

27. Learning Collections

Hi , I have never learned collections before and the books i studied before it was very difficult to understand.I tried head first but its all mixed up like arraylist in some chapter and other things in other chapter. So was thinking whether a book or tutorial can guide me from beginning. Regards Deepak

28. Collections - suggest examples

Start by creating your own Stack interfacepublic interface Stack { int size(); boolean isEmpty(); boolean isFull(); boolean push( ) throws FullStackException; E pop() throws EmptyStackException; E peek() throws EmptyStackException; /** * Before = 1, 2, 3. after = 1, 2 */ boolean drop() throws EmptyStackException; /** * Before = 1, 2, 3. after = 1, 3, 2 */ boolean swap() throws ...

29. Java collections - how frequently do you use them in development ?

how often do any of the experienced developers here use collections in their work ? Please share your usage according to the rating below : 1- So often ( that i remember most of the API and hardly refer the SUN docs) 2- Sometimes (need to refer docs sometimes) 3- Hardly PS : would love to hear from as many people ...

30. Why Collections.emptySet(), Collections.emptyList() & Collections.emptyMap() ?

Alternately, people might just use a constructor to create a new empty set, list, or map, rather than call one of these methods. But the Collections methods offer a couple of advantages: 1. They're more concise because you don't need to explicitly type out the generic type of the collection - it's generally just inferred from the context of the method ...

31. Collection hierarchy

Collection has a method for adding elements. For Map, the only thing that could be added is instances of Map.Entry. But adding any Map.Entry is dangerous, as it requires extra checks to make sure there is no other Map.Entry with the same key. Also, the implementing class of Map.Entry matters. So instead of having Map extend Collection, Map provides three views ...

32. Collections out of range

The following code is an example in K & B. Why are # 5 and 6 "out of range"? # 5 is included in map but why the comment "out of range". why does #6 throw error? TreeMap map = new TreeMap(); map.put("a", "ant"); map.put("d", "dog"); map.put("h", "horse"); SortedMap submap; submap = map.subMap("b", "g"); // #1 create a ...

33. Performing a group by Statement on a Java Collection

I've got very simple Java List of objects. The object would be something like: ... VehicleID, VehicleName, ModelName, ... List vehicleList = new ArrayList(); I want to do a "group by" and count on this Java List on say "VehicleName" and retrieve a count of each of the elements. eg: ... VehilceName: xyzzzz : count: 2 VehilceName: xyzzyyy : count: 10 ...

34. Java Collections

35. Collections

36. Collection program not working as expected

Hi the following program is from Deitel with minor modifications. The method removeColors is just as it is in the book. The colors BLUE,RED,GREEN are expected to be removed but they are still present after the method runs. import java.util.*; public class collTest1{ private static final String [] colors = {"CHARTREUSE","BLUE","RED","GREEN","CYAN"}; private static final String [] removeColors = {"BLUE","RED","GREEN"}; public collTest1(){ ...

37. Collection

38. Collections

Hi... just did javap java.util.List got this result... Compiled from "" public interface java.util.List extends java.util.Collection{ public abstract int size(); public abstract boolean isEmpty(); public abstract boolean contains(java.lang.Object); public abstract java.util.Iterator iterator(); public abstract java.lang.Object[] toArray(); public abstract java.lang.Object[] toArray(java.lang.Object[]); public abstract boolean add(java.lang.Object); public abstract boolean remove(java.lang.Object); public abstract boolean containsAll(java.util.Collection); public abstract boolean addAll(java.util.Collection); public abstract boolean addAll(int, java.util.Collection); ...

39. indexOfSubList in Collections

Hi, I found the logic of indexOfSubList() in Collections is not so correct, as shown below: 1. if source list is not empty and target list is empty, the function returns 0. 2. if source list and target list is empty , the function returns 0. if 0 means the first element, the function should returns -1 as per the above ...

40. How to read csv file & which collection should be used ?

Thanks Rob, I have done following : package csvreader; import; import; import java.util.StringTokenizer; public class ReadCSV { public static void main(String args[]) { try { String csvFile="C:\\Documents and Settings\\Administrator\\My Documents\\Downloads\\Sample_input_lookup_file.csv"; BufferedReader br = new BufferedReader(new FileReader(csvFile)); String line = ""; StringTokenizer st = null; int lineNumber=0; int tokenNumber=0; while((line = br.readLine()) != null) { lineNumber++; st = new StringTokenizer(line,","); ...

41. problem with collection

class PurchaseDetail{ private int item_id; PurchaseDetail(int i){ item_id=i; } public static void main(String[] args){ Purchase purchase=new Purchase(); purchase.purchaseCode=1; List p =new ArrayList(); p.add(new PurchaseDetail(1)); p.add(new PurchaseDetail(2)); p.add(new PurchaseDetail(3)); purchase.purchaseDetail=p; try{ Field f= purchase.getClass().getDeclaredField("purchaseDetail"); List t=(List) f.get(purchase); for(PurchaseDetail d:t){ System.out.println(d.item_id); } }catch (Exception e) { e.printStackTrace(); } } } class Purchase{ int purchaseCode; Date purchaseDate; List purchaseDetail; // this is the hard ...

42. Resizable Collection with Different Types/Classes

I am looking for a way to put references to objects from different classes into an array-like collection that is resizable. I am aware that this is viewed by some as an unwise practice, but I'm all about stupid. I've tried ArrayList, but it seems to store elements as Object types, regardless of what the original objects are that the elements ...

43. illustrate the collections in java

44. Collections

Hi, I have this code Map childFileMap = new HashMap(); childFileMap.put(new Long(1), "aaaaa"); childFileMap.put(new Long(2), "bbbbbb"); childFileMap.put(new Long(3), "ccccccccc"); Iterator childFileMapIterator = (childFileMap.keySet()).iterator(); while (childFileMapIterator.hasNext()) { String jmsChildCorrelationId =; System.out.println("jmsChildCorrelationId========= =="+ jmsChildCorrelationId); String childFileName = childFileMap.get(1); System.out.println("childFileName===========" + childFileName); } I am not able to understand why this System.out.println("childFileName===========" + childFileName); prints null

45. how to use genirics in collection

46. Collection Interator

47. collection

48. Help me on Collection

49. Help collections

50. Qustion about collections

51. collection issue

hi friends i want to store employee data in a collection sorted with employee name. also i want to fetch employees with name starting with a given character. (for character scroll in window) i tried TreeMap with Structure . but it fails to add duplicate entries for a given character. i thought of using subset() method of TreeMap to fetch ...

52. Collections help.

Hey, I'm writing a program that is using an arraylist. I've used Collections.max(arraylist) and Collections.min(arraylist) to return the longest and shortest elements in the arraylist. However, the shortest an element in the arraylist can be is 1, because otherwise the element is empty and is skipped when being counted. How can I get my program to include the empty elements when ...

53. Collection Help

Hi All, I have a program Like this public class sample { public static void main(String[] args) { Collection> collectionMap = getCollectionMap(); Map> map = new HashMap>(); Map insideMap = new HashMap(); insideMap.put("1", "A"); insideMap.put("2", "B"); map.put("Map1", insideMap); map.put("Map2", insideMap); collectionMap.addAll(map.values()); System.out.println(collectionMap); } private static Collection> getCollectionMap() { TreeMap> treeMap = ...

54. Basic CD Collection!

Create a program the will store info about a collection of CD's. Program Elements: Compiles properly CD Class with apropriate fields and methods ArrayList used to store CD objects Menu System for selecting program functions Program Correctly adds a new CD to the collection Program correctly displays the entire CD collection Program correctly saves a CD Collection to a Text File ...

55. Collections

first of all I would like to excuse me for my utter noobness... But I've got the following: List myList = new ArrayList() Now myList is declared as a List but initialized as an ArrayList, my question is, can I use ArrayList methods (not supported by List) on myList? Thx in advance (PS: it is quit possible that this question is ...

56. Collection

57. java collections

58. [HELP] A "collection" in Java

Hello, I don't know if I'm in the right section but here it goes. So in Java you have arrays, which have a certain structure so you can return an object stored in that array at the index you like. But now I'm doing this assignment where we make our own CollectionInterface which stores Indentifiers without any structure. So now I ...

59. Basics on collections

Hi guys, I'm trying to think of the most intelligent way to do the following: I want to write a class that contains a collection Cache of objects of type Member. The Member class is nested within the Cache class. Different classes should be able to call the Cache, but I want to maintain a single static set of the elements ...

60. Cannot find ActionMappings or ActionFormBeans collection

ERROR:- exception org.apache.jasper.JasperException: javax.servlet.ServletException: javax.servlet.jsp.JspException: Cannot find ActionMappings or ActionFormBeans collection org.apache.jasper.servlet.JspServletWrapper.handle JspException( org.apache.jasper.servlet.JspServletWrapper.servic e( org.apache.jasper.servlet.JspServlet.serviceJspFil e( org.apache.jasper.servlet.JspServlet.service(JspSe javax.servlet.http.HttpServlet.service(HttpServlet .java:803) root cause javax.servlet.ServletException: javax.servlet.jsp.JspException: Cannot find ActionMappings or ActionFormBeans collection org.apache.jasper.runtime.PageContextImpl.doHandle PageException( org.apache.jasper.runtime.PageContextImpl.handlePa geException( org.apache.jsp.login_jsp._jspService(login_jsp.jav a:100) org.apache.jasper.runtime.HttpJspBase.service(Http javax.servlet.http.HttpServlet.service(HttpServlet .java:803) org.apache.jasper.servlet.JspServletWrapper.servic e( org.apache.jasper.servlet.JspServlet.serviceJspFil e( org.apache.jasper.servlet.JspServlet.service(JspSe javax.servlet.http.HttpServlet.service(HttpServlet .java:803) root cause javax.servlet.jsp.JspException: Cannot find ActionMappings or ActionFormBeans collection org.apache.struts.taglib.html.FormTag.lookup(FormT org.apache.struts.taglib.html.FormTag.doStartTag(F ...

61. Where to start for studying Collections ?

I am trying to learn Collections as a part of my certification.But the classes and interfaces are so similar and large in number that after 5 days of some intense [:)] study i have only ended up with frustration. Can anyone suggest me some links where i can at least get a good start at Collections. Thanks in Advance.

62. A question on Collections

11. public static Iterator reverse(List list) { 12. Collections.reverse(list); 13. return list.iterator(); 14. } 15. public static void main(String[] args) { 16. List list = new ArrayList(); 17. list.add("1"); list.add("2"); list.add("3"); 18. for (Object obj: reverse(list)) 19. System.out.print(obj + ", "); 20. } What is the result? A. 3, 2, 1, B. 1, 2, 3, C. Compilation fails. D. The code ...

63. Collection

64. Collections question

66. Garbage Collection For Collection

67. Concept with collection

68. Collections dilemma

Hi, I am rather new to collections and have the following problem. I need to store employee names (in order of their surname) along with their department name. I have attempted this and got so far: 1. created TreeMap and added employee names to it( 2 strings). 2. created a list (arrayList), which now holds the the employees in order of ...

69. Collections question

For instance, I have a Set of Cars where the equals method uses a VIN number and License Plate (both Strings) to compare Car instances. Then say I am passed two Strings containing a VIN and License Plate and need to obtain the Car from the Set. Would the best way be to simply iterate over the Set and see if ...

70. Question related to Collections

Believe me on that, I have tried using a while loop over there and my program does not only crashes but freezes my whole computer...With the "if", my method works really fine when the value is found in the set but when a value is not found in the set, it just crashes and that's what I want to avoid!

71. 1.4.2 "wrapping" collections

I should mention the boss's second point on the matter was "If you unit test it properly then such bugs will NOT make it through to production." Fair cop that... except it still leaves the door open for bad/incomplete testing... and no-ones ever been guilty of that, especially when they're under the hammer to punch out a production patch pronto, and ...

72. garbbage collection

73. change a collection while you're iterating...

74. Collection.add(E e); override? what is "E"?

75. Collections

76. Collection - a very basic example

Hi, I want to create a number of objects and place each object into a collection, from which I can then retrieve them using the account number field of that object. However, I can't make head nor tail of any of the tutorials I've been able to find on the internet since none of them have any basic example of how ...

77. Collection swap

78. Collections not compiling

79. usage of collections.. please suggest

thanks for the quick reply, actually I was wondering if it is possible to get the key from and group of values. let me explain the problem a bit.. currently severaly of my keys(the letter strings) are pointing a the same value(the codes) code values 100 "a", "b", "c" is there a way in which my code can be the 'key' ...

80. collection

81. collection choice

I have some elements of type a, b , c ,d ...not in a list and I go through them with a for. What I want to do is, when I see an element of type a, I put it in an array, when i see an element of ype b, i check if there's an element a corresponding with it ...

82. collections problem

83. Collection Cataclysm

Hi, I have encountered a problem re:collections.. basically, i need to know how to access a collection from a collection.. ex. i have a collection of houses in a which has another collection of residents in their respective houses - in a way being able to add/remove "objects" from them. from street i need to know, whom are the residents ...

84. Collection Problem

Item1 - Property1, Property2, Property3 Item2 - null Item3- Property1 How can I call Item1 and receive the 3 properties? The Items are already in a treeSet and the properties can go inside an arrayList as their order is not important. You could even suggest to me to use a hashSet for the properties or whatever collection as long as the ...

85. adding characters to a collection

/** * Inserts item in the NodupBag if space is available; that is, * it the size is less than the capacity. * Returns true if a new element is added and false * if a duplicate value exists. * * @param item element that is added if space is available.. * @return true if a new element is inserted in ...

86. Collection Warning

87. Help required in Collection

Dear All, I am a new user. I am having problem in finding the Collection/Map which support getting key and values both i.e. generally we have .get(Key) method but I want that there should be some function like .getKeys(value) which return all the keys containing that values. I don't want to use loop for this. Is there any Class which allow ...

88. In need of help with Collections.

If you want more information on why using a float or double to represent values like money is a bad idea I'm sure Google will turn something up. It's also entirely possible (perhaps even likely) someone will link to "What every programmer should know about floating point" or whatever the article I see linked alot around here is called.

89. How to implement a custom collection?

90. small doubt regarding collections

91. Help Required with Collections

Hi, I have retrieved a number of records from a database that each contain a "code" and a "value". The code is non-unique, e.g. I have multiple records where the code="A", the code ="B" etc. What I want is a total of all the values per code, e.g. a total of all the values for code A, total of all thecode ...

92. Parametric Collection superclass/subclass

93. Writing a collection

94. Collection.suffle()

95. Java Collections question

Yes, I understand they are overriden but why? What purpose does it have to be overriden? I guess thats what I'm asking. interface Collection{ void A(); } interface Set extends Collection {void A(); void B{};} Class X implments Set{ public void A() {System.out.println("a");} public void B() {System.out.println("b");} public static void main(String args[]) {X x = new X(); x.A(); x.B(); }

96. Java Collection help

You must use a Java Collection object (not an array) to hold the Passengers and this must limit the number of passengers either when the maximum seat number is reached (250 for this demo) or if the maximum weight is reached (21300). An elegant way to do this would be to subclass the Collection class you choose and add extra functionality ...

97. problem iterating through a set collection

Thank you all for your replies. I added the iter variable outside the loop at some stage and forgot/didn't figure to remove it also from within the loop. I appreciate your answers, now I clearly understand where I was going wrong. I wish I had the option to allocate more Duke stars to the topic so I can reward more points... ...

98. Question on Collections

Mr.Goodwill wrote: Why we are often assigning Hashmap to Map Eg: Map m = new HashMap(); Set s = new HashSet(); List l = new ArrayList(); Why we must not use ArrayList a = new ArrayList(); or HashSet h=new HashSet();. I use List and ArrayList as example but the same is applicable to the other cases too. List is an abstraction ...

100. java collections find and replace problem

I don't know how to proceed with that, loop will it be something like this Map types = eMPAssit.getIDMap(empTagAssit.tag_codes); Map eMPTypes = transformStateList(eMPAssit); request.setAttribute("EmploTag", eMPTypes); Iterator iterator = types.keySet().iterator(); while (iterator.hasNext()) { Integer key =; using somewhere like .replace("_", " ") I'm not sure whre to use what ,please kindly assist with an example flounder  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.