Collection class comparation
Dear all,
Could you tell me the performance benmark comparation between the collection class (List, Map, Set, Queue, and also class in java.util.concurrent package...)
Could you give me when to use one class?
Thank a lot for support.
Best regards,
VKnight
VKnight wrote:
Dear all,
Could you tell me the performance benmark comparation between the collection class (List, Map, Set, Queue, and also class in java.util.concurrent package...)There is no "fastest collection." Different collections have different big-O performance metrics in different situations. You'll learn what these are when you learn about the collections.
Could you give me when to use one class? When you study the collections and learn what each one does, you'll understand which one is appropriate to use in which case.
There's plenty of information already available for these very broad questions, in books and on the web. There's no point in somebody repeating it here. After you've done your research, if you have a more specific question, feel free to ask.
Similar Messages
-
The Collections Framework defines several algorithms that can be applied to collections
and maps.These algorithms are defined as static methods within the Collections class.
These algorithms support List,Map,Set,Enumeration,SortedMap,SortedSet.But not
Iterator.
Is it fixed by Java that no Iterator can use within any of those algorithms of Collections
class?
Or, Is it only Maps class support Iterator for it's algorithms?Thanks everybody for replies.
import java.util.*;
public class AlgorithmsDemo {
public static void main(String[] args) {
LinkedList<Integer> ll=new LinkedList<Integer>();
System.out.println("Size of LinkedList ll: "+ll.size());
System.out.println("Contents of LinkedList ll: "+ll);
ll.add(-8);
ll.add(20);
ll.add(-20);
ll.add(8);
System.out.println("Now the size of linkedList ll: "+ll.size());
System.out.println("Now the contents of linkedlist ll: "+ll);
Comparator<Integer> comp=Collections.reverseOrder();
Collections.sort(ll,comp);
System.out.print("List sorted in reverse: ");
for(int i:ll)
System.out.print(i+" ");
System.out.println();
Collections.shuffle(ll);
System.out.print("List shuffled: ");
for(int i:ll)
System.out.print(i+" ");
System.out.println();
System.out.println("Minimum: "+Collections.min(ll));
System.out.println("Maximum: "+Collections.max(ll));
}If I want to use Iterator instead of Comparator then what changes need to do
within above code? -
Confusion... Data Access Object and Collection Class
Please help me...
i have a Book class in the library system, so normally i would have a Collection class eg. BookCollection class which keeps an array/ arrayList of Book objects. In BookCollection class i have methods like
"searchBook(BookID)" which would return me a Book object in the array.
But now i'm confused with Data Access Object... In sequence diagrams there's a "Data Access class" which is used to retrieve data from and send data to a database. So, if i have the Data Access class, do i still need BookCollection class? Because BookCollection serves as a database also rite? ...I think you're in the right rail.
The BookCollection class could be still usefull if you will need to manage search results with more than onne record (e.g.: search by author name). -
When to use abstract class compared to interface
hi
can some one plase advise me when to use abstract class compared to interface?
Example will be appreciated...So an abstract class can carry implementation. This can be used to formulate a rule of thumb as to when to use it over an interface.
If you have a so called type specialization relationship between the subtypes and the supertype then they're likely to benefit from shared implementation provided by the supertype, so use class (abstract or concrete) extension in this case. Type specialization is when the supertype represents a general concept like Fruit and the subtypes are specialized forms of that like Apple and Banana.
Another common kind of relationship is called type expansion. In this case the subtypes are unlikely to have any use of implementation provided by the supertype, so use interface implementation. Type expansion is when the supertype represents a specific character the subtypes take on. For example Apple and Bicycle ure unrelated in the type specialization sense but still can share a common character like Comparable. The subtypes have been expanded to include the supertype character, namely the ability to be compared. -
Has anyone out there used a good set of collection classes for Forté?
I know about the Brahma Fortify product (very good, very expensive!) and I
have heard of a product from Born, but I can't get hold of it yet.
I'd love to hear from anyone who has
a) used the Born collection classes
or
b) knows of other sets of collection classes
many thanks,
Tim Kimber
EDS (UK)
To unsubscribe, email '[email protected]' with
'unsubscribe forte-users' as the body of the message.
Searchable thread archive <URL:http://pinehurst.sageit.com/listarchive/>Hi,
We had a similar requirement some time back and were
evaluating what is available in the market. We then used Born's
collection
classes and found it quite useful. However, since our requirements
were very specific, we developed our own set of collection classes.
I feel Born's colleciton classes are a good place to start. Even if you
want to buy an out-of-the-shelf suite, it will give you an idea of what
you can expect and what you cannot.
Born's classes are FREE and provide an interface-based library of useful
collection classes, including sorted arrays, linked lists, binary trees,
iterators and filters.
You can get the collection classes by sending an email message to
[email protected] with a subject line of "Born Collections"
and the message "Send Born Collections" in the body of the message. The
software and documentation will be sent back to you.
Hope this helps!
Ajith Kallambella M.
Forte Systems Engineer,
Internationational Business Corporation.
From: General[SMTP:[email protected]]
Reply To: General
Sent: Monday, June 08, 1998 12:21 PM
To: [email protected]
Subject: Collection classes for Forte
Has anyone out there used a good set of collection classes for Forté?
I know about the Brahma Fortify product (very good, very expensive!)
and I
have heard of a product from Born, but I can't get hold of it yet.
I'd love to hear from anyone who has
a) used the Born collection classes
or
b) knows of other sets of collection classes
many thanks,
Tim Kimber
EDS (UK)
To unsubscribe, email '[email protected]' with
'unsubscribe forte-users' as the body of the message.
Searchable thread archive
<URL:http://pinehurst.sageit.com/listarchive/>
To unsubscribe, email '[email protected]' with
'unsubscribe forte-users' as the body of the message.
Searchable thread archive <URL:http://pinehurst.sageit.com/listarchive/> -
I have import two classes class1, class2 in a Class3 program. Class1 contains get and set methods. Class2 and Class3 coding is as follows. In Class2, I have passed the Class1 object. Now my problem is when I try to get the values in Class3 through get method of class1 using Collection class, I get only null values. Kindly tell me how to correct my problem.
class c2
public Collection selecting(Class1 c1) throws Exception
ResultSet rs = null;
PreparedStatement ps = null;
Connection con = null;
Collection result = new ArrayList();
con = getConnection();
id = c1.getId();
String sql = "select * from table1 where id=?";
ps = con.prepareStatement(sql);
ps.setInt(1,id.intValue());
rs = ps.executeQuery();
while(rs.next())
c1.setName("Name"));
c1.setDesc("Desc"));
result.add(c1);
} class c3
public static void main(String[] arg)
e=Integer.valueOf(request.getParameter("id"));
c1.setCategoryId(e);
Collection sel = c2.selecting(c1);
Iterator i = sel.iterator();
while(i.hasNext())
s=c1.getName();
f=c1.getDesc();
out.println("<b> "+s+","+f+"<br>");
}Don't Mistake me. I have send only a part of program. I have used return statement in my program. I need solution for ,how to get the values from Collection class object when a class object is passed as argument.
Collection sel = c2.selecting(c1);Here c1 is object of class1 which contains methods like
getName(),
getDesc(),
setName(),
setDesc(); -
Help needed with collection classes
Howdie all,
I'm new to Java, and for the most part, I can do it.
I'm stuck on how to do the following:
I have to write a program that simulates a deck of cards, including shuffling (involving cards are re-collected), dealing cards. I have to create 52 objects of the card class. The only things that I can use involve some of the collection classes (arrays, dynamic lists, vectors, dictionaries), queues/stacks
I dont know:
** what to use. should i use a dyn list or a vector
**how the heck would i shuffle the cards?
** for dealing the cards, i figued i would just use a loop to draw a set of cards (face and suit)
i am not asking for code on how to do it (though pseudo-code/alogorithm may help). i just dont know where to start..i am totally stuck.
thanks a bunch!I would suggest you to use the LinkedList class for the deck representation.
To create the cards you could use
for i = 0 to 51
new Card(i);
In Card constructor do something like
int colour = i/13+1; // (1-4, one for each colour)
int value = i%13+1; // (1-13, ace-king)
To shuffle you could
for i = 0 to 100
j = radom(52)
k = random(52)
swap(card#j, card#k)
This will swap 2 random cards 100 times.
To draw cards
Card c = cards.remove(0)
or
Card c = cards.remove(radom(cards.size()))
In the later, the shuffle part is not really needed.
thought about this some more and now i have another
question:
when using a dyn linked library, i am not even sure
how to create the 52 objects. previously when doing
project like this, i just used a random function to
generate the cards, and used switch statements for the
non-numbered cards and for the suite. how would i do
accomplish this when using a collection class?
Howdie all,
I'm new to Java, and for the most part, I can do it.
I'm stuck on how to do the following:
I have to write a program that simulates a deck of
cards, including shuffling (involving cards are
re-collected), dealing cards. I have to create 52
objects of the card class. The only things that Ican
use involve some of the collection classes (arrays,
dynamic lists, vectors, dictionaries),queues/stacks
I dont know:
** what to use. should i use a dyn list or avector
**how the heck would i shuffle the cards?
** for dealing the cards, i figued i would just usea
loop to draw a set of cards (face and suit)
i am not asking for code on how to do it (though
pseudo-code/alogorithm may help). i just dont know
where to start..i am totally stuck.
thanks a bunch! -
Collection classes, count
I am attempting to count occurances of a string being added in a collection class. This is what I have
class CountOccurrencesListener implements ActionListener
public void actionPerformed(ActionEvent event)
String target = targetText.getText( );
feedback.append(target + " occurs ");
int answer = countOccurrences(answer);
feedback.append(answer + " times.\n");
public int countOccurrences(String target, int answer)
int index;
answer = 0;
for (index = 0; index < manyItems; index++)
if (target == data[index])
answer++;
return answer;
It should count how many times a string was added from the text field, TargetText, but I get this error message:
"BagApplet.java": Error #: 300 : method countOccurrences(int) not found
any ideas on what I am doing wrongTo cure that error, change "int answer = countOccurrences(answer)" to:
int answer = countOccurrences(target,answer);
You either left out some code in your post or you will find additional errors. -
Find best collection class for the scenarios given
Hi Everyone,
Can u help me in answering this questions:
Indicate the most efficient / appropriate standard Java (JDK 1.4 or lower) collections class for each requirement. Do not use any classes that are not in the standard JDK (e.g. Apache commons-collections classes).
2.1. An un-ordered, unique collection
2.2. An insertion-ordered, non-unique collection
2.3. A sorted, unique collection
2.4. An insertion-ordered, unique collection
2.5. Random access to elements within a list
2.6. Insertion into random points within a list
2.7. A last-in-first-out queue
Please let me know what u think ?
IF possible please tell me the reason why u selected one over the other
Thanks in advance....2.1. An un-ordered, unique collection
HashSet thereadOkay, why?
2.2. An insertion-ordered, non-unique collection
LinkedList thereadOkay, why?
2.3. A sorted, unique collection
TreeSet theread
TreeMap kv pair thereadOkay, but is collection with a small "c" or Collection with a captial "C"? Maps don't implement the Collection interface. In a general sense, you could consider them collections, but in Java land, usually that implies single-valued groupings--i.e., those that implement Collection.
>
2.4. An insertion-ordered, unique collection
LinkedHashSet theread
LinkedHashMap thereadSame comments as above.
2.5. Random access to elements within a list
LinkedList (In fact any class that implements List
Interface)No. Hint: Do you know what "random access" means, and why LinkedList is not a good choice?
2.6. Insertion into random points within a list
LinkedHashSet
LinkedHashMapNo. It doesn't say anything about uniqueness or k/v pairs.
2.7. A last-in-first-out queue
StackOkay.
2.8. List any of these classes which are not
thread-safe, if any. How
would you make these Collections thread-safe?
HashSet, LinkedList, TreeSet, TreeMap, LinkedHashSet,
LinkedHashMapI'm not going to match 'em all up one by one, but it seems about right.
This is typically accomplished by synchronizing on
some object that naturally encapsulates the collection
class. If no such object exists, the map should be
"wrapped" using the Collections.synchronizedMap
method. This is best done at creation time, to prevent
accidental unsynchronized access to the map:
Map m = Collections.synchronizedMap(new TreeMap(...));Sounds about right. Also sounds like it was copied and pasted. If so, do you understand it? -
The Born Collection Classes were given away at the recent Forte' Central
Users Group meeting. Born's Forte' National Practice would like to
extend their availability to anyone who might benefit from them. They
are published under the GNU software license so they can be used by all
but can not be sold for profit. Please read the included licensing
agreement for complete details.
The software includes the collection, container, iterator, and filter
classes as well as a user manual and technical design documentation.
The collection classes provide standard collection behavior such as
sorting and filtering and are based on a very flexible interface driven
design. Born has used the collection classes in conjunction with the
development of a new Forte' Release 3 based framework. The Born
Collection Classes do require Forte' Release 3.0.
To receive the software, simply send an email to
'[email protected]' with a subject of 'Born Collections' and a
message body containing 'Send Born Collections'.
It is free software so we are not offering technical support. However,
any feedback or questions you might have can be emailed to
'[email protected]'.Have a look at [http://commons.apache.org/math/userguide/stat.html#1.5%20Statistical%20tests]. Does anybody know a free library that contains the wilcoxon and mann-whitney test.
-
Are Collection classes synchronized.
I learned from the ver 1.2, which was the first to add collections framework that the collection classes were not synchronized and as such a programmer had to do it manually.
What about in 1.4 and 1.5? Plz guide me.
or
plz give me some docs/links of help.There is a Collection class, which is the base class for all collections (such as List, Set, Map). Then there is a Collections class...which is like a Collection utility class...actually, i thin that's exactly what it is. If so, they should have called it CollectionUtil...when i first saw this class..it was confusng at first...then i noticed the "s" in Collection
THe "Collections" class provides method to synchronize your "collection"
List list = new ArrayList(); // unsynchronize list
list = Collections.synchronizedList(list); the 2nd line basically, say...use the collection utility class to create a wrapper around the list objject and make the list synchronized....return the wrapper 9wich is a synchronized list)
to iterate over the collection
synchronized(list) {
Iterator i = list.iterator(); // Must be in the synchronized block
while (i.hasNext())
foo(i.next());
}example taken from the Sun Java Collections API -
To sort 15000 values,which kind of a collection class should i use
To sort 15000 values,which kind of a collection class should i use15000 values isn't that much; you could use a SortedSet if all values
are unique, otherwise simply use an ArrayList and Collections.sort()
it afterwards.
kind regards,
Jos -
Define custom typed collection class
Hi, I would like to define a custom typed collection class that can hold multiple type elements, to be more concrete, i have a class defined as
public class MyList extends ArrayList{
public class TestMyList{
MyList<MyDataTypeOne> listOne; // i want to use JAVA generics here, but it wont let me
MyList<MyDataTypeTwo> listTwo;
}and i got an error saying: "MyList" does not have typed parameters.
I understand that i need to declare my class as something like
public class MyList<MyDataTypeOne> extends ArrayList
but i dont want it to be restricted to <MyDataTypeOne> but multiple types, just like ArrayList. How can i cope with this please, thanks!Test the following code:
import java.util.ArrayList;
public class MyList<E> extends ArrayList<E>{
public MyList()
public static void main(String[] args) {
MyList<String> lista = new MyList<String>();
lista.add("Bolivia");
String x = lista.get(0);
System.out.println(x);
} -
Comparison insertion/search time between different Collection class
Hi,
Does someone know where I can find a clear an complete comparison between different JAVA class which implements interface Collection?
I want to compare:
- elements insertion time
- elements search/removal time
Thank you very much in advance
Diegofrom wikipedia: Its purpose is to characterize a function's behavior for very large (or very small) inputs in a simple but rigorous way that enables comparison to other functions.
meaning if I ask how quick an algorithm is you might say it completes in 10 seconds but the next time you run it it might take 8 seconds. It kind of depends on what else your computer is doing/ how fast your computer is or how much data you are putting through ie if the puter has little memory it might need to use virtual memory which will have an effect on your performance.
Big O notation identifies how much work has to be carried out. The easiest example is a simple search of an array:
for (int i = 0; i < array.length; i++) {
if (array[i] == "weijewr") {
return i;
}Where n represents a number of elements:
This takes O(n) (big Oh of N) as potentially you need to look at each element.
if you were to write a standard bubble sort it would be O(n2) as potentially you need to iterate the array once for each element. -
Error in struts with collection classes
Hi All,
I have tried to list all the employee through dabase search i have created with strus logic tag in search.jsp page
as following
<bean:size id="size" name="searchForm" property="results"/>
<logic:equal name="size" value="0">
<center><font color="red"><b>No Employees Found</b></font></center>
</logic:equal>
<logic:greaterThan name="size" value="0">
<table border="1">
<tr>
<th>Name</th>
<th>Social Security Number</th>
</tr>
<logic:iterate id="result" name="searchForm" property="results">
<tr><td><bean:write name="result" property="name"/></td>
<td><bean:write name="result" property="ssNum"/></td>
</tr>
</logic:iterate>
</table>
</logic:greaterThan>
</logic:present>
2. The following class shows ActionServlet as SearchAction.java class
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,HttpServletResponse response)
throws Exception
EmployeeSearchService service = new EmployeeSearchService();
List results=new ArrayList();;
SearchForm searchForm = (SearchForm) form;
// Perform employee search based on what criteria was entered.
String name = searchForm.getName();
if (name != null && name.trim().length() > 0)
results = service.searchByName(name);
/* else {
results = service.searchBySsNum(searchForm.getSsNum().trim());
// Place search results in SearchForm for access by JSP.
searchForm.setResults(results);
// Forward control to this Action's input page.
return mapping.getInputForward();
3. The following class created for search the employee as EmployeeSearchService.java
Note: This file will implement EmployeeDB.java for database connections and also the values are return using Employee.java as for get and set method of name and id..
EmployeeSearchService.java
public List searchByName(String name)
// List returnList=new ArrayList();
List results=new ArrayList();
EmployeeDB em=new EmployeeDB();
results=em.searchName(name);
ListIterator langIt=results.listIterator();
while(langIt.hasNext())
Employee emp=(Employee) langIt.next();
String name2 = emp.getName();
String SSNo=emp.getSsNum();
System.out.println("Emp Name:"+ name2);
results.add(name2);
results.add(SSNo);
4. EmployeeDB.java contain the following code..
public class EmployeeDB extends AbstractDAO
public List searchName(String name1)
{ //External Interface
List resultList = new ArrayList();
ResultSet resultSet = null;
Statement aStmt2 = null;
String url="jdbc:odbc:test";
String uname="root";
String pwd="root";
String name="";
try {
Connection con=getConnection();
aStmt2 = con.createStatement();
String query2 = "SELECT SSNO,NAME FROM EMPLOYEE WHERE NAME ='"+ name1 +"'";
cat.debug(query2);
resultSet = aStmt2.executeQuery(query2);
while(resultSet.next()){
Employee tvo = new Employee();
name = resultSet.getString("NAME");
String SsNum1 = resultSet.getString("SSNO");
tvo.setName(name);
tvo.setSsNum(SsNum1);
resultList.add(tvo);
catch (Exception e) {
System.out.println( e);
e.printStackTrace();
return resultList;
My Problem is all the classes are compiled and excute and validation work fine but while the name of employee entered that if name is available in DB table which reply the following error message as,
javax.servlet.ServletException
org.apache.struts.action.RequestProcessor.processException(RequestProcessor.java:516)
org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:423)
org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:226)
org.apache.struts.action.ActionServlet.process(ActionServlet.java:1164)
org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:415)
javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:362)
root cause
java.util.ConcurrentModificationException
java.util.AbstractList$Itr.checkForComodification(AbstractList.java:449)
java.util.AbstractList$Itr.next(AbstractList.java:420)
com.dao.vertex.EmployeeSearchService.searchByName(EmployeeSearchService.java:77)
com.dao.vertex.SearchAction.execute(SearchAction.java:36)
org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:421)
org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:226)
org.apache.struts.action.ActionServlet.process(ActionServlet.java:1164)
org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:415)
javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:362)
note The full stack trace of the root cause is available in the Apache Tomcat/5.5.9 logs
Plz reply how to solve send correct code to send data to values of iterate bean.... which line of code i need to modify...
Thanks.So here is what you are doing:
ArrayList results = //get employees from database
ListIterator langIt = results.listIterator();
while (langIt.hasNext()) {
Employee emp = langIt.next();
String name2 = emp.getName();
String SSNo = emp.getSSNum();
results.add(name2);
results.add(SSNo);
}So you get a list or Employee objects, then you get an iterator over the list. For each Employee in the list you add the name and SSNo as Strings back to the same list. From the API for ConcurrentModificationException the exception can be thrown when you modify a collection while iterating over the collection - which is precisely what you are doing.
The ListIterator interface allows you to modify the list through its own methods. Try using:
langIt.add(name2);
langIt.add(SSNo);instead.
Why are you taking the name and SSNo out of the Employee object and placing them back in the same List anyway? That makes no sense to me.
Maybe you are looking for
-
Including helper classes in java proxy jar file
I must not be using the right header search criteria because I'm sure this question has been asked before. In a Web Service File (.jws) I've imported a couple of helper classes that function as data transfer objects. I did this to maintain consistenc
-
Links are not working on a website
I am unable to access links in the bar at the top of the page of the www.braveheartedgospel.com website. Thank you for your help.
-
Blocking a particular customer for immediate delivery creation
Hi All, I have the following requirement Right now whenever the sales orders comes from the customers through EDI, the deliveries were created immediately. This was set up through the sales document. This is being used for the document KE. Now we nee
-
Multiple endpoints for HTTP adapter (OracleAS 10g - 10.1.2)
The HTTP adapter documentation states the HTTP adapter supports sending outgoing messages for Interconnect to multiple HTTP endpoints. This enables sending messages to various remote web servers. The HTTP user guide states: "An endpoint is associated
-
Profit Center Interface with PRCMAS01
Has anyone built an interface for profit center data using PRCMAS01? I didn't see a BUKRS field for company code assignment in the IDoc. How is the company code assigned to a profit center via an interface? Surely this is a standard process during