Re: Determine index from array reference?
Patricia Shanahan wrote:
Knute Johnson wrote:
Is there a way to determine the index of an array element given a
reference?
Object[] obj = new Object[8];
Object q = obj[2];
Is it possible to get 2 from q other than iterating through all values
of obj[] and testing for equality of the reference?
Thanks,
This type of question always seems a little backwards to me. I tend to
think the other way round. Not "How do I do this with an array?" but "I
need to do these accesses. What data structure should I use?".
Why an array? What other operations are being done on it?
Patricia
Thanks everybody for your replies. And since Patricia asked the big
question maybe I should give up some more information about what exactly
I'm trying to do.
I asked about an array because that's what I have now. An array of
JTextFields that have ActionListeners attached. In the AL I need to
update another array. So what I had done in the past was to extend
JTextField and add an int variable to hold an index value for the
JTextField. I added a getIndex() method and in my ActionListener I use
that method to acquire the index to modify my other array.
So I could have checked the JTextField reference against all the others
in the array and gotten an index that way but that didn't sound a whole
lot better than the way I was getting it now.
The little program below appears to work with a Vector. What do you
think of that approach?
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class test1 {
public static void main(String[] args) {
Vector<JTextField> v = new Vector<JTextField>();
JTextField test = null;
for (int i=0; i<10; i++) {
JTextField tf = new JTextField(" ",10);
v.add(tf);
if (i == 3)
test = tf;
}
System.out.println(v.indexOf(test));
System.out.println(v.indexOf(null));
}
}
Anyway, if anybody has a better idea I'm all ears.
Thanks,
--
Knute Johnson
email s/nospam/knute/