Results 1 to 2 of 2

Thread: method not working in java

  1. #1
    Join Date
    Jun 2006
    Location
    Miami, FL
    Beans
    789
    Distro
    Ubuntu 10.10 Maverick Meerkat

    method not working in java

    guys, the toArray method is not working, could someone tell me why
    Thanks

    Code:
    package com.javablackbelt.utils;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.List;
    
    public class ListUtils {
    	
    	public static void main(String arg[]) {
    		String[] arr = {"one", "two", "three", "four", "five"};
    		ArrayUtils.print(arr);
    		
    		System.out.println();
    		
    		String [] reversedArr = ArrayUtils.reverse(arr);
    		ArrayUtils.print(reversedArr);
    		
    		System.out.println();
    		
    		ArrayList<String> list = ArrayUtils.toArrayList(arr);
    		ListUtils.print(list);		
    		
    		ArrayList<String> reversedList = ListUtils.reverse(list);
    		ListUtils.print(reversedList);
    		
    		String[] arrFromList = ListUtils.toArray(list);
    		//ArrayUtils.print(arrFromList);
    		
    	}
    	
    	public static void print(ArrayList<String> aStr) {
    		System.out.print("list: [ ");
    		for(String l: aStr)
    			System.out.print(l+" ");
    		System.out.println(" ] size: "+aStr.size());
    	}
    	
    	public static ArrayList<String> reverse(ArrayList<String> aList) {
    		ArrayList<String> newList = aList;
    		
    		Collections.reverse(newList);
    		return newList;
    	}
    	
    	public static String[] toArray(ArrayList<String> list) {
    		ArrayList<String> newList = list;
    		String[] newStr = (String[]) newList.toArray();
    		
    		return newStr;
    	}
    
    }
    looking for tips and tutorials, checkout
    http://www.pctechtips.org

  2. #2
    Join Date
    Mar 2010
    Location
    London
    Beans
    924

    Post Re: method not working in java

    Firstly, to understand this you should read up a little on generics in Java. While the List API does offer the method you have shown, it returns an array of type Object. I suggest you use the method explained here instead.

    You would need something more like this:

    Code:
    public static String[] toArray(ArrayList<String> list) {
        ArrayList<String> newList = list;
        String[] newStr = newList.toArray(new String[newList.size()]);
    		
        return newStr;
    }
    - "Make me a coffee..."
    - "No"
    - "sudo make me a coffee"
    - "OK"

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •