How can I check if my Input String is in my ArrayList?
I did it like this. But it always shows "not equal". Althoug I insert 1 for example:
public class Main {
public static void main(String[] args) {
String Input = JOptionPane.showInputDialog("Input:");
ArrayList<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
if (Input.equals(list)) {
JOptionPane.showMessageDialog(null, "equals");
} else {
JOptionPane.showMessageDialog(null, "not equal");
}
}
}
If you want to check does List<T> contains T item you should use yourList.contains(T item) in your code, you are using item.equals(object) which is completely different. In short what equals() does is it checks do both objects are stored in the same memory address. Although for some default classes this method is overwritten and works a different way, String class is a good example of that.
Explanation
You wrote
if (Input.equals(list)) { ... }
with Input being a String and list an ArrayList. But, the String#equals (documentation) method compares if two Strings have the same characters (like "hello".equals("hello")), not if the argument list contains the element you called the method on. To quote from its documentation:
Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
Solution
What you actually want to use is List#contains (documentation):
Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that Objects.equals(o, e).
So the code might look like:
if (list.contains(Input)) { ... }
Naming convention
Please note naming conventions. Variable names should always be in camelCase, so input instead of Input. Same for method names.
Only class names are written in PascalCase. And constants (static final) are written in uppercase SNAKE_CASE.
Related
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 2 years ago.
I want to change an element name in an ArrayList, without changing its value.
Like :-
ArrayList<Integer> array1 = new ArrayList<>();
int num = 1;
array1.add(num);
Now I want to change num to number, but it's value will be 1.
(Is it possible?)
I want to display all the elements in a ArrayList in a swing combo box, but some of the variables show strange names, such as "Client#45673...". But I want the user to see a descriptive name. That is why I want to rename the variables.
OK, so you are wandering up the proverbial garden path with your "change the name of a variable".
Firstly, it is not a variable. When you put something into a collection, Java doesn't remember that at one point you had the value in a variable.
Secondly, values in general and objects in particular don't have names ... unless you specifically implemented some kind of "name" field as part the class definition.
But I think the clue is in this sentence:
... but some of the variables show strange names, such as "Client#45673..."
That's not a name! That looks like the output of the default implementation1 of toString that your Client class is inheriting from java.lang.Object.
If you want to print / display something something more meaningful, your Client class needs to override the toString() method with its own implementation.
For example:
public class Client {
private String myDescription;
public Client(...) {
...
myDescription = /* something */
}
#Override
public String toString() {
return myDescription;
}
}
Your toString method can return anything you want it to ... so long as it is represented as a string.
Incidentally, if you were to print the array1 object in your question, you would see the actual value 1 rather than a "name" (as you called it). This is because java.lang.Integer overrides the toString() method.
1 - The default toString() result consists of the internal class name and the object's identity hashcode value. The latter is a magic number that the JVM generates. It is not guaranteed unique, but it is guaranteed that it won't change for the lifetime of the object. At any rate, you cannot alter the string that is generated by that method ... except by overriding it.
What you're talking about is the output when printing an object. Those objects need to override toString() and return whatever string is deemed appropriate that describes the class or the contents thereof.
Try this.
class Foo {
//#Override
//public String toString() {
// return "This is a foo";
//}
}
Foo f = new Foo();
System.out.println(f);
Now uncomment the toString() method and print it again.
To print arrays, one way is to use Arrays.toString()
int[] arr = {1,2,3,4};
System.out.println(Arrays.toString(arr));
I have an enum like that:
public enum Lang {
TR("tr"),
EN("en"),
SE("se");
private String langName;
private Lang(String langName) {
this.langName = langName;
}
}
at another class I want to check whether a langName exists or not. If I put a getter method I can iterate over langNames:
for (Lang langEnum : Lang.values()) {
langEnum.getLangName();
}
However my enum may be too long and I don't want to iterate over an array. I want to use a Map or Set. On the other hand I don't want to another variable within my enum.
How can I check whether my enum has a langName or not?
Well, if every enum constant represents a language (as the code seems to suggest), then I would use an EnumSet.
Set<Lang> langs = EnumSet.allOf(Lang.class);
And then I can check if a language is already there. Like
if(langs.contains(Lang.EN) {
//...
}
Not sure if this is the answer you were looking for. The contains method of EnumSet would not even iterate over the internal collection. The internal collection would be stored in an array and finding an element is calculated based on a hash. So, this in fact, should achieve what you requested in the question.
How about using valueOf?
Lang lang = null;
try {
lang = Lang.valueOf(enumName);
// enum exists
} catch (IllegalArgumentException e) {
// enum does not exist
}
Since your enum name is just the language name capitalized, you can just capitalize the language name and pass it into valueOf.
public static boolean containsAll(String[] strings, String test)
{
if (test == null || strings.length == 0) {
return false;
}
for (String str : strings)
if (!test.contains(str))
return false;
return true;
}
I have no idea what I can add to a boolean inside the parentheses but I have this line of function in my script with help from a fellow SOF member.
Thing is, how do I know what to write in a parenthesis to declare stuff? I don't know the rules from my memory and I don't have any source I can relate to. Basically I have no idea why there is an array and a string declared in the parentheses.
Basically,
1) Why is there a line declaring an array and a string inside the parentheses?
2) Where can I relate to as a source to get more information about classes like "boolean" and what I can do to change their functions? Basically I want a book-like website I can relate to whenever I don't know about something in java.
Why is there a line declaring an array and a string inside the parentheses?
So that you can use those parameters within the method , to achieve something .
From the method declaration it seems :
public static boolean containsAll(String[] strings, String test)
The method tries to search for a String passed as parameter test within an array passed as parameter strings and returns boolean true or false depending on whether the strings array contains the test String or not. Or probably , the method was named containsAll() to signify that it ascertain whether all the elements of strings array contains test string !
EDITED: The method checks if all the elements of the strings array contains the test String.
Where can I relate to as a source to get more information about classes like "boolean" and what I can do to change their functions
boolean is primitive , Boolean is a wrapper class. Your method returns boolean primitive.
I have this problem where there are several parts in my code where I check if these certain conditions are met so that I can understand if what I am checking is of one type or the other. this ends up becoming large if else trees because I am making lots of checks, the same checks in each method, and there are several different types the thing I am checking can be. This I know can be solved using objects!
Specifically, the things I am checking are 4 string values from a file. based on these string values, the 4 strings together can make one of 3 types. Rather than making these same checks every time I need to get the type the 4 strings make up, I am wondering if I can create a general object given these 4 strings and then determine if that object is an instanceof either specific class 1, 2, or 3. Then I would be able to cast that general object to the specific object.
Say I name the general object that the 4 strings create called Sign. I would take those 4 strings and create a new Sign object:
Sign unkownType = new Sign(string1, string2, string3, string4);
I need to check which specific type of sign this sign is.
EDIT:
for more detail, the Signs I am checking are not symbols like "+" or "-", they are signs with text like you would see on the road. there are 4 lines on each sign and they need to be checked to see if each line evaluates to match a specific type of sign.
The first line of SignType1 will be different of the first line of SignType2, and I want to take those 4 lines (Strings) and pass it onto an object and use that object throughout my code to get the values from it rather than making the same checks in each method.
If you want me to show some code, I can, but it won't make much sense.
What you seem to asking for is a factory pattern
public interface ISign {
public void operation1();
public void operation2();
}
and a Factory class to generate classes based on input
public class SignGenerator {
public static ISign getSignObject(String str1,String str2, String str3, String str4) {
if(str1.equals("blah blah"))
return new FirstType();
if(str1.equals("blah blah2") && str2.equals("lorem ipsum"))
return new SecondType();
return new ThirdType();
}
}
public class FirstType implements ISign {
}
public class SecondType implements ISign {
}
public class ThirdType implements ISign {
}
Implement all Type specific logic in these classes so you can call them without checking with tons of if..else clauses first
From what I gathered from your statement.
Say: create the method that returns a certain object provided the given string is equal to whateva value you specify
//provided the objects to be returned are subtypes of Sign
public Sign getInstance(String first, String second, String third, String fourth)
{
if(first==null || second==null || third==null || fourth===null )
return null;
if(compare1.equals(first))
return new SignType1();
else
if(compare2.equals(second))
return new SignType2();
else
if(compare3.equals(third))
return new SignType3();
else
if(compare4.equals(fourth))
return new SignType4();
}
Above code checks and returns thee appropriet instance corresponding to the string passed
Hope that's what was your concern
{
List list= new ArrayList();
list.add("one");
list.add("second");
System.out.println(list);
}
How can the object "list" be used like it has been in the print statement? Don't we need to use the object to access a method to print the list?
prinln(someObject) will print out whatever is implemented in someObject's toString() method.
You can use toString() which is (supposed) to be implemented for all objects:
System.out.println(list.toString())
Note that you ought not to use the returned string as anything you can actually parse; it's really for a visual representation. It also doesn't need to uniquely represent the object.
When you write
System.out.println(list)
you are, in fact, using the toString() method implicitly.
Docs Says about toString() in Collections:
Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by String.valueOf(Object).
When we pass any object to println() method, it will implicitly call that object's toString() method. So, what is actually executed is
System.out.println( list.toString() );
ArrayList is inherited from the class java.util.AbstractCollection and that class has toString() method. So, in your case, that toString() should be executed.
That toString() method returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by String.valueOf(Object).
Looking at your question and comments, I think your confusion ultimately stems from you being unsure how printing works. In general in such cases, I recommend to get the JDK sources and simply take look inside.
In this case, we would first go to the System class and check out the out member (because println is called on System.out):
public final class System {
...
public final static PrintStream out = null;
Since we know now that out is a PrintStream, let's check out that class:
public class PrintStream extends FilterOutputStream
implements Appendable, Closeable
{
...
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
(we know it's calling this method, since the other println signatures don't match the type List)
OK, so we see that println converts the given Object (your List in this case) to a String using String.valueOf(Object). Let's check out that method:
public final class String {
...
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
So now we know that your List's toString() method is used to generate the output. As others have pointed out, it is overriden in ArrayList to provide the output you see.
It can be used like this because class List inherits the Object class, and the Object class has the toString() method, which means every object can be turned into a String.
printing a list directly will give the the string representation of the list.
If you want to access the objects in the list you need to use iterator or loops or advanced for loops for collections.
e.g.
for(String s : list){
System.out.println(s);
}
Well you can study and try out all the list methods to modify it. e.g. add, remove.
Also if you are printing an object, then toString() method is implicitly called.
You can loop through all the items in the list in order to print them out. you can do this using a while loop of a for loop.
while (list.hasNext) {
System.out.println((String) list.next());
}
for(String i in list){
System.out.println(i) ;
}
Not sure if this is what your looking for but its an option.
Yo need toString() method. when you print object Reference , by default toString() method is called. If you look at toString() method by default it prints
getClass().getName() + '#' + Integer.toHexString(hashCode())
Now as per your requirements you can override this to print the values in list(String Class overrides it too)
Here you are creating List interface.So it will allow to add duplicate values in list also.Also we can directly print object like System.out.println(obj);
And inside the List class the, toString method is being overridden so that it will print all its contents rather than the address of the object.
System.out.println(Arrays.toString(myList.toArray()));