Return a String from an ArrayList

edited November 2013 in How To...

Is there a simple way to return a string from an arrayList? Do you have to first convert ArrayList to String? How do we do this?

For instance....

String compareNodes () {
  for(int z=0; z < finalNodes.size(); z++){
    for(int x=0; x < firstNodes.size(); x++){
      if (finalNodes.get(z).equals(firstNodes.get(x))) {
        println("We found link " + firstNodes.get(x) + " in finalNodes: " + finalNodes.get(z) + " that is numberArray " + z );
        println("how we go here 1..."); 

        String holder = (String)firstNodes.get(x);
        foundConnection(); 
        exit(); 

        return holder;
      }
    }
  }
}

Answers

  • Answer ✓

    Do you have to first convert ArrayList to String? How do we do this?

    it's called 'casting'

    this is fine: String holder = (String)firstNodes.get(x);

    however, you can also tell it the type when you create the ArrayList:

    List<String> myList = new ArrayList<String>();

    then it knows that anything fetched by get(i) will be a String so you can just

    String holder = firstNodes.get(x);

    without the need to cast.

  •     exit();
    
        return holder;
    

    In the above code, the second line will never be reached...

    You can also use the toString() method, if what you put in the list isn't already strings:

    String holder = firstNodes.get(x).toString();
    

    As said, it depends on what these lists hold.

Sign In or Register to comment.