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 wrong

To 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.

Similar Messages

  • 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).

  • 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.

  • Collection classes for Forte

    Has anyone out there used a good set of collection classes for Fort&eacute;?
    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&eacute;?
    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/>

  • Collection Class

    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!

  • 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?

  • Free Born Collection Classes

    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

  • Collection Classes

    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

  • About Collections class

    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?

  • 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);
    }

  • 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.

  • Custom Collection Class

    Hello people!
    In VB.NET, i am used to creating collections of custom objects that inherit from the CollectionBase class. I'm new to java, but i need a custom collection. I need to be able to add and get the index of items in the collection.. at least. so i'm guessing it'll implement the List implementation.. yeah? I dunno.. and what's all this "<E>" stuff that i keep seeing around all about?! :) lol
    Thank you for your time! - Callam

    - What exactly are your requirements? I don't really understand it? Do you just want to find out the index of an item in the collection? Simple: Any List can do that.
    - the <E> stuff you keep seeing is about generics. If you plan to implement your own collection you should definitely read through the generics tutorial first.

  • Can't generate setters for array or collection classes with JAXB

    I am trying to use JAXB to generate the required setters for Spring beans. Although according to the book Java & XML Data Binding
    Chapter 3 page 42 by Brett McLaughlin it was possible with DTD's using
    <?xml version="1.0"?>
    <xml-java-binding-schema version="1.0-ea">
    <options package="javajaxb.generated.movies" default-reference-collection-type="array" />
    <element name="movies" type="class" root="true"/>
    </xml-java-binding-schema>
    to generate an array as in
    public Movie[] getMovie( ) {
    // implementation
    public void setMovie(Movie[] _Movie) {
    it doesn't look like that capability exists with JAXB 2.0 and XML Schemas. In their wisdom they just generate getters on Lists and tell you:
    <p>
    * This accessor method returns a reference to the live list,
    * not a snapshot. Therefore any modification you make to the
    * returned list will be present inside the JAXB object.
    * This is why there is not a <CODE>set</CODE> method for the filingForm property.
    * <p>
    * For example, to add a new item, do as follows:
    * <pre>
    * getFilingForm().add(newItem);
    * </pre>
    Of course this doesn't work for Spring injection where setters are needed.
    Does anyone know different or is there a way of getting around this ?
    I've tried constructor injection in Spring but it's not as convenient and involves extensive coding of generated code (not nice).
    Edited by: user3806112 on Mar 15, 2011 11:13 AM

    Oh I found it on this post
    http://cxf.547215.n5.nabble.com/NPE-in-generated-setter-method-when-collectionType-quot-indexed-quot-and-a-null-array-is-used-td3323012.html
    collectionType="indexed" in the globalBindings-tag
    it works in schema internal global bindings as well
    <jaxb:globalBindings collectionType="indexed" >

Maybe you are looking for

  • Why is my iPhone 5s not responding to taps at times?, Why is my iPhone 5s not responding to taps at times?

    There are times when I tap the green phone icon to make a call and it doesn't respond or do anything.  This has also happened when playing "Words with Friends" when I press the "play" button.  I don't seem to have this issue with anything else on my

  • How to pass a header variable in jsp

    Hi , I am using Headervariable login module(which takes user id form http header variable) for single sign on. I configured the login module stack. But to test i need a jsp from which i can pass the user id in http header. to test if i am able to set

  • Problem: THX Config resetting after each pc rest

    Setup: I'm using the console from the original install disc, but the driver is the latest web-download driver, version 02.09.006 from 9th of oct. 2006. I'm using the original consoles because they are much more intuiti've and I can even set more thin

  • Mounting drives

    Fairly generic Linux question but does my non-root user have to belong to any specific groups to be able to mount the disk drive and usb drives? Whenever I try to access one as my non-root user I get a "Not Authorized" message box (in GNOME).

  • App download help

    So for the last few days I can't download new apps from iTunes i can update old ones but when I try to download new ones it says the terms an agreements have changed and click here to view I click it but I alwYs says unable to load page. And o can't