简体   繁体   中英

How do I call a method in java from main?

import java.util.*;

import java.io.*;

public class Test extends ArrayList
{

    ArrayList<String> list = new ArrayList<String>();

    public static void main(String[] args)
    {
        new Test().add();
        new Test().contains();
    }



    public boolean add(){
        list.add("cat");
        System.out.println(list);
        return true;
    }

    public void contains(){
        if (list.contains("cat")){
            System.out.println("list contains cat");
        }
        else{
            System.out.println("list doesn't contain cat");
        }

    }

}

Why isn't the result [cat] list contains cat? It keeps giving me [cat] list doesn't contain cat. The first method is working correctly, but why isn't the second one? Thanks... I'm really new to this.

That's because you're calling both the methods with different instances.

new Test().add(); // Creates 1 instance
new Test().contains(); // creates another instance

You need to use the same instance to call both the methods.

Test t = new Test();
t.add();
t.contains();

Every new Test object created with by the new Test() has its own copy of list . That's why when you call contains() with the other instance, its still empty as the list of the first instance was only added with the string "cat".

because the arraylist is not static, so you are creating two instances of App where each one has its own list variable.

set the variable static and it will work.

static ArrayList<String> list = new ArrayList<String>();

But it is better to use the same instance to call two times.

Test test = new Test();
test.add();
test.contains();

You're calling new Test() twice. You are creating two instances. You're adding to the first, and checking for contains on the second (newly-created) one.

You are creating two instances of Test. Then you create two separate instances of "list". First with the String "cat" and the second one empty.

Why do you want to extend ArrayList? May be you can try like this...

import java.util.ArrayList;

public class Test {

    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("cat");
        System.out.println(list);

        if (list.contains("cat")) {
            System.out.println("list contains cat");
        } else {
            System.out.println("list doesn't contain cat");
        }     

    }  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM