java - How to access elements in a generic arraylist of arrays -


i have been trying access elements of several arrays held within array list. able access regularly, problem comes when use generic type e account different data types. gives me class cast exception. if change type of tempstart , tempscan , corresponding casts int[] (since using pass in) runs.

public static <e> arraylist<e> removeduplicates(arraylist<e> list) {     if (list.get(0).getclass().isarray()) {         system.out.println(" array!");         //go through arrays , make sure          //not same, remove same         //make flag see if different         boolean matching;         (int idx = 0; idx < list.size() - 1; idx++) {             e[] tempstart =(e[])list.get(idx);             (int k = idx + 1; k < list.size(); k++) {                 matching = true;                 e[] tempscan = (e[])list.get(k);                 (int index = 0; index < tempstart.length; index++) {                     if (tempstart[index] != tempscan[index]) {                         matching = false;                     }                 }                 if (matching) {                     list.remove(tempscan);                     k--;                 }             }         } 

you trying cast e e[] , it's not correct. try like:

import java.lang.reflect.array ... public static <e> arraylist<e> removeduplicates(arraylist<e> list) {     arraylist<e> retlist = new arraylist<>(list.size());     if (list.isempty()) return retlist;     if (list.get(0).getclass().isarray()) {         boolean matching;         (int idx = 0; idx < list.size() - 1; ++idx) {             e tempstart = list.get(idx);             (int k = idx + 1; k < list.size(); k++) {                 matching = true;                 e tempscan = list.get(k);                 int tempstartlen = array.getlength(tempstart);                 (int index = 0; index < tempstartlen; index++) {                     if (array.get(tempscan, index) != array.get(tempstart, index)) {                         matching = false;                     }                 }                 if (matching) {                     list.remove(tempscan);                     k--;                 }             }         }         return retlist;     } else {         throw new illegalargumentexception("list element type expected array");     } } 

however because using java reflection array manipulate array operation, using generic e doesn't make sense here. can simple declare arraylist<object>

updates: @afsantos comments below, parameter type arraylist declared arraylist<?> nothing going insert it.


Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -