Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem with Array Value - Comparing Arrays.

 
Dixon Alexander
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have an array
array1[] that has 3 values.
example: dog
cat
chicken
String[] array1 = {"dog", "cat", "chicken"};

What I need to do use a if statement in this situation?
Example:
if (array1 == "dog" ) {
println("is a dog");
}
OR
if (array1.equals("dog")) {
println("is a dog");
}
Can any of these, too be possible, How, I try both cases show above but they don't work.
Thanks.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're comparing the array object to a String; they're definitely not equal. You want to compare one element, or all the elements, to the String. To compare one particular element, you'd use
if (array1[1].equals("dog"))
To compare them all, you could use a for loop, or the following trick:
if (Arrays.asList(array1).contains("dog"))
using the "asList()" static method in the java.util.Arrays class.
 
Dixon Alexander
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.util.*;
public class TestingArrays {
public TestingArrays() {
}
public static void main(String[] args) {
TestingArrays tt = new TestingArrays();
String[] parentid = {"1", "1", "1", "dog", "cat"};
String str = new String("1");
// Fixed-size list
List list = Arrays.asList(parentid);
// Growable list
list = new LinkedList(Arrays.asList(parentid));
Vector v = new Vector();
for ( int i=0; i<parentid.length; i++ ) {
v.add(parentid[i]);
}
System.out.println("v : " + v);
Enumeration e = v.elements();
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
}
System.out.println("list.size(): " + list.size());
System.out.println("list.contains(str) " + list.contains(str));
System.out.println("");
System.out.println("array size: " + parentid.length);
for ( int i=1; i<= parentid.length; i++) {
if (Arrays.asList(parentid).contains("2")) {
System.out.println("la la la: " );
}
}
}
}
 
Dixon Alexander
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
IN THE ABOVE SAMPLE PROGRAM
I like to prove that I have three "1" and then a "cat" and a "dog"
.....
I wanna be able to run a sql query where if the userID="1"
I like to perform a different behavior than if ther userID="something else".
"1" is a default value in the database table for users.
Thanks.
 
Gabriel White
Ranch Hand
Posts: 233
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if (Arrays.asList(array1).contains("dog"))

Thanks for the tip Ernest
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic