[java] make arrayList.toArray() return more specific types

So, normally ArrayList.toArray() would return a type of Object[]....but supposed it's an Arraylist of object Custom, how do I make toArray() to return a type of Custom[] rather than Object[]?

This question is related to java arrays object types arraylist

The answer is


Like this:

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

String[] a = list.toArray(new String[0]);

Before Java6 it was recommended to write:

String[] a = list.toArray(new String[list.size()]);

because the internal implementation would realloc a properly sized array anyway so you were better doing it upfront. Since Java6 the empty array is preferred, see .toArray(new MyClass[0]) or .toArray(new MyClass[myList.size()])?

If your list is not properly typed you need to do a cast before calling toArray. Like this:

    List l = new ArrayList<String>();

    String[] a = ((List<String>)l).toArray(new String[l.size()]);

It doesn't really need to return Object[], for example:-

    List<Custom> list = new ArrayList<Custom>();
    list.add(new Custom(1));
    list.add(new Custom(2));

    Custom[] customs = new Custom[list.size()];
    list.toArray(customs);

    for (Custom custom : customs) {
        System.out.println(custom);
    }

Here's my Custom class:-

public class Custom {
    private int i;

    public Custom(int i) {
        this.i = i;
    }

    @Override
    public String toString() {
        return String.valueOf(i);
    }
}


A shorter version of converting List to Array of specific type (for example Long):

Long[] myArray = myList.toArray(Long[]::new);

I got the answer...this seems to be working perfectly fine

public int[] test ( int[]b )
{
    ArrayList<Integer> l = new ArrayList<Integer>();
    Object[] returnArrayObject = l.toArray();
    int returnArray[] = new int[returnArrayObject.length];
    for (int i = 0; i < returnArrayObject.length; i++){
         returnArray[i] = (Integer)  returnArrayObject[i];
    }

    return returnArray;
}

 public static <E> E[] arrayListToTypedArray(List<E> list) {

    if (list == null) {
      return null;
    }
    int noItems = list.size();
    if (noItems == 0) {
      return null;
    }

    E[] listAsTypedArray;
    E typeHelper = list.get(0);

    try {
      Object o = Array.newInstance(typeHelper.getClass(), noItems);
      listAsTypedArray = (E[]) o;
      for (int i = 0; i < noItems; i++) {
        Array.set(listAsTypedArray, i, list.get(i));
      }
    } catch (Exception e) {
      return null;
    }

    return listAsTypedArray;
  }

Questions with java tag:

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error Instantiating a generic type When to create variables (memory management) java doesn't run if structure inside of onclick listener String method cannot be found in a main class method Are all Spring Framework Java Configuration injection examples buggy? Calling another method java GUI I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array Java and unlimited decimal places? Read input from a JOptionPane.showInputDialog box Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable Two Page Login with Spring Security 3.2.x Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java) Got a NumberFormatException while trying to parse a text file for objects Best way for storing Java application name and version properties Call japplet from jframe FragmentActivity to Fragment Comparing two joda DateTime instances Maven dependencies are failing with a 501 error IntelliJ: Error:java: error: release version 5 not supported Has been compiled by a more recent version of the Java Runtime (class file version 57.0) Why am I getting Unknown error in line 1 of pom.xml? Gradle: Could not determine java version from '11.0.2' Error: Java: invalid target release: 11 - IntelliJ IDEA Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util Why is 2 * (i * i) faster than 2 * i * i in Java? must declare a named package eclipse because this compilation unit is associated to the named module How do I install Java on Mac OSX allowing version switching? How to install JDK 11 under Ubuntu? Java 11 package javax.xml.bind does not exist IntelliJ can't recognize JavaFX 11 with OpenJDK 11 Difference between OpenJDK and Adoptium/AdoptOpenJDK OpenJDK8 for windows How to allow all Network connection types HTTP and HTTPS in Android (9) Pie? Find the smallest positive integer that does not occur in a given sequence Error: JavaFX runtime components are missing, and are required to run this application with JDK 11 How to uninstall Eclipse? Failed to resolve: com.google.firebase:firebase-core:16.0.1 How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

Questions with arrays tag:

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array? How to update an "array of objects" with Firestore? How to increment a letter N times per iteration and store in an array? Cloning an array in Javascript/Typescript use Lodash to sort array of object by value TypeScript enum to object array How do I check whether an array contains a string in TypeScript? How to use forEach in vueJs? Program to find largest and second largest number in array How to plot an array in python? How to add and remove item from array in components in Vue 2 console.log(result) returns [object Object]. How do I get result.name? How to map an array of objects in React How to define Typescript Map of key value pair. where key is a number and value is an array of objects Removing object from array in Swift 3 How to group an array of objects by key Find object by its property in array of objects with AngularJS way Getting an object array from an Angular service push object into array How to get first and last element in an array in java? Add key value pair to all objects in array How to convert array into comma separated string in javascript Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0) Angular 2 declaring an array of objects How can I loop through enum values for display in radio buttons? How to convert JSON object to an Typescript array? Angular get object from array by Id Add property to an array of objects Declare an array in TypeScript ValueError: all the input arrays must have same number of dimensions How to convert an Object {} to an Array [] of key-value pairs in JavaScript Check if a value is in an array or not with Excel VBA TypeScript add Object to array with push Filter array to have unique values remove first element from array and return the array minus the first element merge two object arrays with Angular 2 and TypeScript? Creating an Array from a Range in VBA "error: assignment to expression with array type error" when I assign a struct field (C) How do I filter an array with TypeScript in Angular 2? How to generate range of numbers from 0 to n in ES2015 only? TypeError: Invalid dimensions for image data when plotting array with imshow()

Questions with object tag:

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor How to iterate (keys, values) in JavaScript? What’s the difference between “{}” and “[]” while declaring a JavaScript array? Check if value exists in the array (AngularJS) How to write data to a JSON file using Javascript Why is "forEach not a function" for this object? How to remove undefined and null values from an object using lodash? Creating a static class with no instances What is the difference between ( for... in ) and ( for... of ) statements? How do I print my Java object without getting "SomeType@2f92e0f4"? How can I return the difference between two lists? How do I correctly setup and teardown for my pytest class with tests? Javascript - removing undefined fields from an object Python iterating through object attributes How to iterate through an ArrayList of Objects of ArrayList of Objects? transform object to array with lodash What's the difference between integer class and numeric class in R Check if object value exists within a Javascript array of objects and if not add a new object to array How to get the difference between two arrays of objects in JavaScript Mapping a JDBC ResultSet to an object javascript find and remove object in array based on key value How to create multiple class objects with a loop in python? How to delete an instantiated object Python? How can I remove an element from a list, with lodash? JavaScript: Create and destroy class instance through class method Zoom to fit: PDF Embedded in HTML Creating multiple objects with different names in a loop to store in an array list Creating object with dynamic keys Get specific object by id from array of objects in AngularJS How to parse JSON with VBA without external libraries? iterating through json object javascript How to get the hours difference between two date objects? How to sort an array of objects in Java? how to use javascript Object.defineProperty Get specific objects from ArrayList when objects were added anonymously? How to copy JavaScript object to new variable NOT by reference? error C2220: warning treated as error - no 'object' file generated passing object by reference in C++ Get values from an object in JavaScript How to convert a string to JSON object in PHP Parse JSON response using jQuery

Questions with types tag:

Cannot invoke an expression whose type lacks a call signature How to declare a Fixed length Array in TypeScript Typescript input onchange event.target.value Error: Cannot invoke an expression whose type lacks a call signature Class constructor type in typescript? What is dtype('O'), in pandas? YAML equivalent of array of objects in JSON Converting std::__cxx11::string to std::string Append a tuple to a list - what's the difference between two ways? How to check if type is Boolean How do I find numeric columns in Pandas? No function matches the given name and argument types How do I print the type or class of a variable in Swift? Get data type of field in select statement in ORACLE Determine the data types of a data frame's columns How to concatenate columns in a Postgres SELECT? TypeError: 'str' object cannot be interpreted as an integer Can pandas automatically recognize dates? how to check if the input is a number or not in C? Pointtype command for gnuplot Change column type in pandas Determining type of an object in ruby Hashmap holding different data types as values for instance Integer, String and Object Where in memory are my variables stored in C? Defining TypeScript callback type What MySQL data type should be used for Latitude/Longitude with 8 decimal places? Use of Custom Data Types in VBA How to cast Object to its actual type? How can I get the data type of a variable in C#? When and where to use GetType() or typeof()? BOOLEAN or TINYINT confusion Convert String to Type in C# Passing just a type as a parameter in C# How to check if variable's type matches Type stored in a variable Where to find the complete definition of off_t type? How To Change DataType of a DataColumn in a DataTable? C# Return Different Types? What's the difference between primitive and reference types? How to check if a class inherits another class without instantiating it? Float vs Decimal in ActiveRecord Check if a value is an object in JavaScript Which data type for latitude and longitude? What data type to use for money in Java? Convert a byte array to integer in Java and vice versa C++ auto keyword. Why is it magic? java : convert float to String and String to float How to round up integer division and have int result in Java? Better way to get type of a Javascript variable? TypeError: 'float' object is not callable Double precision floating values in Python?

Questions with arraylist tag:

Adding null values to arraylist How to iterate through an ArrayList of Objects of ArrayList of Objects? Dynamically adding elements to ArrayList in Groovy How to replace existing value of ArrayList element in Java How to remove the last element added into the List? How to append elements at the end of ArrayList in Java? Removing Duplicate Values from ArrayList How to declare an ArrayList with values? In Java, can you modify a List while iterating through it? Load arrayList data into JTable How to quickly and conveniently create a one element arraylist Difference between size and length methods? Creating multiple objects with different names in a loop to store in an array list Passing ArrayList from servlet to JSP How to add an object to an ArrayList in Java Create an ArrayList with multiple object types? Storing and Retrieving ArrayList values from hashmap Array vs ArrayList in performance Simple way to compare 2 ArrayLists how to fix java.lang.IndexOutOfBoundsException Get specific objects from ArrayList when objects were added anonymously? How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it? How to sort an ArrayList in Java How to use an arraylist as a prepared statement parameter Create an ArrayList of unique values How to find an object in an ArrayList by property Java ArrayList of Doubles Pass Arraylist as argument to function How to create an 2D ArrayList in java? Add ArrayList to another ArrayList in java Java - How to access an ArrayList of another class? Getting Index of an item in an arraylist; How to sort an ArrayList? Sum all the elements java arraylist Java Compare Two List's object values? Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList? How to find the minimum value in an ArrayList, along with the index number? (Java) Arraylist swap elements Get value (String) of ArrayList<ArrayList<String>>(); in Java Option to ignore case with .contains method? add item in array list of android Add multiple items to already initialized arraylist in java How to dynamically add elements to String array? What is the difference between List and ArrayList? Can not deserialize instance of java.util.ArrayList out of VALUE_STRING Java ArrayList clear() function How to remove element from ArrayList by checking its value? Java ArrayList - Check if list is empty How to concat two ArrayLists? Foreach loop in java for a custom object list