indexOf


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2

Thread: indexOf

  1. #1
    Join Date
    Nov 2005
    Posts
    1

    Thumbs up indexOf

    Hi all
    i have an arrayList of elements (string), i want to be ablew to retrieve the indexOf any element.
    I have tried this but errors

    public E indexOf (int index){
    if (index<0 || index>=size)
    throw new IndexOutOfBoundsException(""+index);

    for(int i=0; i<size;i++ )
    if (E[]theArray[i] = theArray[index])
    r = theArray[index];
    return r;
    }

  2. #2
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    ??

    You say arraylist, but you show ordinary arrays here ?

    Anyway, the elements int the arraylist must either be
    String, Boolean, Character or numeric (Integer, Float...) for the indexOf to
    work, or the you have to have the
    Code:
    public boolean equals (Object ob)
    method implemented in the class that you store in the list

    Check this out
    Code:
    import java.util.*;
    /**
     * Find index of an object in an arraylist
     */
    class SomeClass {
      public String name=null;
      public int iD=-1;
      public SomeClass(String name, int iD) {
        this.name=name;
        this.iD=iD;
      }
    
      public boolean equals(Object ob) {
        if (!(ob instanceof SomeClass)) {
            return false;
        }
        SomeClass sC=(SomeClass)ob;
        return name.equals(sC.name) && iD == sC.iD;
      }
    
    }
    
    public class AList {
      ArrayList list=new ArrayList();
      public AList() {
        SomeClass sC1=new SomeClass("ABC",123);
        SomeClass sC2=new SomeClass("DEF",223);
        SomeClass sC3=new SomeClass("GHI",323);
        SomeClass sC4=new SomeClass("JKL",423);
    
        list.add(sC1);
        list.add(sC2);
        list.add(sC3);
        list.add(sC4);
    
        // this one would manage without the equals method,
        // its found by reference (address) value
        System.out.println("sC3 index: "+list.indexOf(sC3));
    
        // this one misses (returns -1) without the equals method.
        SomeClass sC5=new SomeClass ("GHI",323);
        System.out.println("sC5 index: "+list.indexOf(sC5));
      }
      public static void main(String[] args) {
        AList al=new AList();
      }
    }
    eschew obfuscation

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center