Convert LinkedList to Array


package com.javadb.examples;

import java.util.LinkedList;
import java.util.List;

public class Main {
    
    public void convertLinkedListToArray() {
        
        List theList = new LinkedList();
        theList.add("Apples");
        theList.add("Bananas");
        theList.add("Oranges");
        theList.add("Grapes"); 
        
        String[] fruits = theList.toArray(new String[0]);
 
        for (int i = 0; i <>
            System.out.println(fruits[i]);
        } 
    }

 
    public static void main(String[] args) {

        new Main().convertLinkedListToArray();
    }



 

We could also have done the conversion like this:


        String[] fruits = new String[theList.size()];
        theList.toArray(fruits);


The output looks like this:


Apples
Bananas
Oranges
Grapes

0 comments:

                                                                

Site Meter