如何在另一个函数中获取ArrayList值?

时间:2015-03-27 13:09:58

标签: java methods arraylist

我是Java的新手,所以我对一些逻辑很困惑。我有一个数组列表(对于一个对象与否)然后我想执行一种函数(它叫什么?方法?iefunctionExample)并从ArrayList中获取值。 这是一个示例代码。对不起,如果我不清楚。我想我错过了公众和事物。 (不要打扰没有var初始化和声明......)

package sampleclass;

import java.util.ArrayList;
import java.util.List;

public class SampleClass {

    public static void functionExample(){
        display = obj.add("something");

        System.out.println(display);

        //or
        obj.get(1);
    }

    public static void main(String[] args) {
        List<Class> obj = new ArrayList<>();

        functionExample();
    }

}

2 个答案:

答案 0 :(得分:1)

你去!尝试探索代码。

package sampleclass;

import java.util.ArrayList;
import java.util.List;

public class SampleClass {

   public static void functionExample(List<String> obj){
      obj.add("something");
      obj.add("nothing");

      System.out.println(obj);

   }

   public static void main(String[] args) {
      List<String> obj = new ArrayList<>();

      functionExample(obj);
   }
}

答案 1 :(得分:1)

package sampleclass;

import java.util.ArrayList;
import java.util.List;

public class SampleClass {

  public static void functionExample(List<String> obj){
    // Adding items to arrayList
    obj.add("something");
    // Adding items to arrayList by position
    obj.add(2, "Something more by position");

    //removing data
    obj.remove(0);

    // Checking index of an item
    int pos = list.indexOf("Item2");

    // Checking if array obj is empty 
    boolean check = obj.isEmpty(); 
    System.out.println("Checking if the arraylist is empty: " + check); 
    // Converting ArrayList to Array
    String[] newArray = obj.toArray(new String[obj.size()]);
    System.out.println("My new great array: "  + Arrays.toString(newArray)); 


    // Getting the size of the obj 
    int size = obj.size(); 
    System.out.println("The size of the list is: " + size); 

    //using foreach loop
    for (String str : obj) {
        System.out.println("Item is: " + str);
    }

    // Replacing an element
    obj.set(1, "My Element 1");
    System.out.println("The arraylist after the replacement is: " + obj); 
  }

  public static void main(String[] args) {
    List<Class> obj = new ArrayList<>();

    functionExample(obj);
  }
}