tags:

views:

351

answers:

8

How can you get the index number in Java?

Example which is not working

class masi { 
         public static void main( String[] args ) { 
             char[] list = {'m', 'e', 'y'};

             // should print 1
             System.out.println( list[] == "e" );                                                                                                           
         } 
     }
+8  A: 

In this case, you could create e new String from your array of chars and then do an indeoxOf("e") on that String:

System.out.println(new String(list).indexOf("e"));

But in other cases of primitive data types, you'll have to iterate over it.

Bart Kiers
Much better than looping.
Dave Jarvis
But very constrained to the specific example given here with chars.
Joey
Hence my remark "...in other cases of primitive..."
Bart Kiers
**How can you use the code in the following situation?** `int indexNumber = new String(letters).indexOf(result[i])` I get *cannot find symbol*.
Masi
That's because class String does not have an indexOf method that takes a char. There is one that takes an int. See the API doc of class String. `int indexNumber = new String(letters).indexOf((int) result[i])`
Jesper
@Jesper: The value of `result[i]` is `String` if it cannot be `char`. It seems that there is no way of using `.indexOf((String) result[i])`.
Masi
:-P int indexNumber = (new String(letters)).indexOf(result[i])
Mead
+3  A: 

Hi Masi. I believe the only sanest way to do this is to manually iterate through the array.

for (int i = 0; i < list.length; i++) {
  if (list[i] == 'e') {
    System.out.println(i);
    break;
  }
}
Matt Solnit
+5  A: 

That's not even valid syntax. And you're trying to compare to a string. For arrays you would have to walk the array yourself:

public class T {
  public static void main( String args[] ) {
    char[] list = {'m', 'e', 'y'};

    int index = -1;

    for (int i = 0; (i < list.length) && (index == -1); i++) {
        if (list[i] == 'e') {
            index = i;
        }
    }

    System.out.println(index);
  }
}

If you are using a collection, such as ArrayList<Character> you can also use the indexOf() method:

ArrayList<Character> list = new ArrayList<Character>();
list.add('m');
list.add('e');
list.add('y');

System.out.println(list.indexOf('e'));

There is also the Arrays class which shortens above code:

List list = Arrays.asList(new Character[] { 'm', 'e', 'y' });
System.out.println(list.indexOf('e'));
Joey
The `asList` method probably had the best combination of brevity, performance and generalality.
skaffman
Took me a while to find it, sorry :-). Haven't done Java in some time and C# is so much nicer in handling such things :-)
Joey
It technically is valid syntax, but not really logical semantics of any sort.
aperkins
I very much doubt there is a `list` type you can build an array from. If there is, naming conventions are gravely violated.
Joey
`List` defineas a `toArray` method
skaffman
That was a reply to aperkins who apparently gave me a downvote for my statement that `list[] == "e"` was invalid syntax. For the `[]` to work, `list` has to be a type, not a variable. That's what I meant with "`list` type to build an array from". Sorry for the misunderstanding.
Joey
+3  A: 

The problem with your code is that when you do

 list[] == "e"

you're asking if the array object (not the contents) is equal to the string "e", which is clearly not the case.

You'll want to iterate over the contents in order to do the check you want:

 for(String element : list) {
      if (element.equals("e")) {
           // do something here
      }
 }
Peter Nix
+1  A: 

Very Heavily Edited. I think either you want this:

class CharStorage {
    /** set offset to 1 if you want b=1, o=2, y=3 instead of b=0... */
    private final int offset=0;
    private int array[]=new int[26];

    /** Call this with up to 26 characters to initialize the array.  For 
      * instance, if you pass "boy" it will init to b=0,o=1,y=2.
      */
    void init(String s) {
        for(int i=0;i<s.length;i++)
            store(s.charAt(i)-'a' + offset,i); 
    }

    void store(char ch, int value) {
        if(ch < 'a' || ch > 'z') throw new IllegalArgumentException();
        array[ch-'a']=value;
    }

    int get(char ch) {
        if(ch < 'a' || ch > 'z') throw new IllegalArgumentException();
        return array[ch-'a'];
    }
}

(Note that you may have to adjust the init method if you want to use 1-26 instead of 0-25)

or you want this:

int getLetterPossitionInAlphabet(char c) {
    return c - 'a' + 1
}

The second is if you always want a=1, z=26. The first will let you put in a string like "qwerty" and assign q=0, w=1, e=2, r=3...

Bill K
I need to have alphabets in the array like: a -> 1, b -> 2,..., z -> 26. - I am coding just for fun, not for homework assignment.
Masi
Your solution suggests me that I need to have 26 hashMap commands. Is there any way of combining the hashmaps commands?
Masi
Hey, if you just want to know if a is 1, b is 2, just use "charValue-'a'+1"! I thought you wanted to actually have different values, or store things in buckets.
Bill K
A: 

If the initial order of elements isn't really important, you could just sort the array, then binarySearch it:

import java.util.Arrays;

class masi { 
    public static void main( String[] args ) { 
        char[] list = {'m', 'e', 'y'};
        Arrays.sort(list);

        // should print 0, as e is now sorted to the beginning
        // returns negative number if the result isn't found
        System.out.println( Arrays.binarySearch(list, 'e') );
    } 
}
R. Bemrose
The order matters in my case. My example is more simple than the problem which I have currently in hand. I have 26 letters actually in the list from a, b, ... to z.
Masi
+2  A: 

Now it does print 1

class Masi {
    public static void main( String [] args ) {
         char [] list = { 'm', 'e', 'y' };

         // Prints 1
         System.out.println( indexOf( 'e', list ) );
    }

    private static int indexOf( char c , char [] arr ) {
        for( int i = 0 ; i < arr.length ; i++ ) {
            if( arr[i] == c ) { 
                return i;
            }
         }
         return -1;
     }
 }

Bear in mind that

"e"

is an string object literal ( which represents an string object that is )

While

'e'

Is a character literal ( which represents a character primitive datatype )

Even when

list[]

Would be valid Java ( which is not ) comparing the a character element with a string element would return false anyway.

Just use that indexOf string function and you could find any character within any alphabet ( or array of characters )

OscarRyz
+2  A: 

I think you can one-line this:

int index = Arrays.asList(list).indexOf('e');

If index >= 0 then you have the first-occuring value, otherwise the char is not in the list.

You need to be careful because it's a list of char's and your index check method is using a string ("e" is a string, 'e' is a character).

Aidos