In Java Methode mit generic input und output basteln?

berndoa

Top Contributor
Hallo, ich poste vorab mal Code ohne den man nicht versteht was ich meine. Nicht abschrecken lassen, sieht länger und böser aus als er ist 🙂

Java:
    public static ArrayList<ArrayList<ArrayList<Long>>> copy3 (ArrayList<ArrayList<ArrayList<Long>>> Array){
        //Sei Array das alte arraylistgebilde
        ArrayList<ArrayList<ArrayList<Long>>> copy = new ArrayList<ArrayList<ArrayList<Long>>>();

        for (ArrayList<ArrayList<Long>> Arrayi : Array) {
            ArrayList<ArrayList<Long>> copyi = copy2(Arrayi);
            copy.add(copyi);
        }
        //copy hat nun die selben inhalte wie array und das ohne referenzen
        return copy;
    }
    
    public static ArrayList<ArrayList<Long>> copy2 (ArrayList<ArrayList<Long>> Array){
        //Sei Array das alte arraylistgebilde
        ArrayList<ArrayList<Long>> copy = new ArrayList<ArrayList<Long>>();

        for (ArrayList<Long> Arrayi : Array) {
            ArrayList<Long> copyi = copy1(Arrayi);
            copy.add(copyi);
        }
        //copy hat nun die selben inhalte wie array und das ohne referenzen
        return copy;
    }
    
    public static ArrayList<Long> copy1 (ArrayList<Long> Array){
        //Sei Array das alte arraylistgebilde
        ArrayList<Long> copy = new ArrayList<Long>();
        for (long Arrayi : Array) {
                Long a=new Long(Arrayi);
                copy.add(a);
        }
        //copy hat nun die selben inhalte wie array und das ohne referenzen
        return copy;
    }


Dies sind 3 FUnktionen. eine bildet eine deep copy einer arraylist, eine bildet eine deep copy einer arraylist aus arraylisten, und die extremste bildet eine deep copy einer arraylist aus arraylists aus arraylists.

im prinzip sind die funktionen ja ziemlich gleich.
Ich stelle mir das wie eine zwiebel vor:
im innersten ist eine arraylist mit long elementen.

dann geht man hin und macht einer äussere shcicht drum herum, ein arraylist<...> kommt aussen drum.
dann noch eine shcicht und noch eine.

dieses "eine äussere shcicht hinzufügen" ist praktisch identisch, sieht man ja auch im code wo von der einen zur anderen funktion überall nur ein arraylist<...> mehr aussendrum ist.

darum kam in mir gerade so die frage auf ob man nicht irgendwie eine generische funktion schreiben kann bei der bspw. der Parameter G für eine beliebig geschachtelte Arraylist<Arraylist<Arraylist<.........Arraylist<Long>.....>>> steht und die Funktion eben dann so die Signatur
static Arraylist<G> copy(ArrayList<G>) hat und entsprechend auch innendrin aufgebaut ist.

weil aktuell muss ich ja für jede anzahl an äusseren schichten eine eigene, wenngleich auch fast identische funktion schreiben.

und wenn ich hier sowas wie eine generische funktion bauen könnte, nicht unähnlich dem prinzip der rekursion, dann wäre das echt nice 🙂


Geht sowas in java?
Ich hatte mal irgendwann von generischen klasen und so gelesen aber mir das nicht so wirklich gemerkt. daher dachte ich, gibts so das pprinzip vielleicht auch für funktionen 🙂
 
In Java ist es nach meinem Wissen nicht möglich, so etwas ohne Code-Generierung zu machen.

Rekursion wäre die einzige Lösung.
 
In Java ist es nach meinem Wissen nicht möglich, so etwas ohne Code-Generierung zu machen.

Rekursion wäre die einzige Lösung.
Wie würde man das machen?


Ich bin gerade beim Suchen auf die Seite https://www.baeldung.com/java-generics und auf sowas wie

Java:
public <T> List<T> fromArrayToList(T[] a) {   
    return Arrays.stream(a).collect(Collectors.toList());
}

gestoßen wobei ich nicht im Geringsten verstehe was da steht.

könnte man sowas da irgendwie nehmen für meine Zwecke? 🙂
 
So wäre es unter Verlust der Typsicherheit möglich:
[CODE lang="java" title="ArrayList Kopieren rekursiv"]import java.util.ArrayList;
import java.util.Random;

public class NestedCopyVariableNestingDepth
{
public static <T> ArrayList<T> deepCopy(
final ArrayList<T> listToCopy ,
final int nestingDepth )
{
if ( nestingDepth < 1 )
{
throw new IllegalArgumentException( "illegal nesting depth " + nestingDepth );
}

if ( nestingDepth == 1 )
{
@SuppressWarnings("unchecked")
final ArrayList<T> result = (ArrayList<T>) listToCopy.clone();
return result;
}

final ArrayList<T> result = new ArrayList<>( listToCopy.size() );

for ( final T element : listToCopy )
{
@SuppressWarnings("unchecked")
final ArrayList<T> castedElement = (ArrayList<T>) element;

final ArrayList<T> elementCopy =
deepCopy(
castedElement ,
nestingDepth - 1 );

@SuppressWarnings("unchecked")
final T castedElementCopy = (T) elementCopy;

result.add( castedElementCopy );
}

return result;
}

public static void main(String[] args)
{
final ArrayList<ArrayList<ArrayList<Long>>> listToCopy = new ArrayList<>( 16 );

fill(
listToCopy ,
3 );

final ArrayList<ArrayList<ArrayList<Long>>> copy =
deepCopy(
listToCopy ,
//nestingDepth
3 );

if ( ! listToCopy.equals( copy ) )
{
throw new RuntimeException( "not equal" );
}

System.out.println( "ok" );
}

private static final Random random = new Random();

private static void fill(
// raw type
final ArrayList listToFill ,
final int nestingDepth )
{
if ( nestingDepth < 1 )
{
throw new IllegalArgumentException( "illegal nesting depth " + nestingDepth );
}

if ( nestingDepth == 1 )
{
for ( int i = 0 ; i < 16 ; i++ )
{
listToFill.add( random.nextInt() );
}

return;
}

for ( int i = 0 ; i < 16 ; i++ )
{
// raw type
final ArrayList listToAdd = new ArrayList<>( 16 );

fill(
listToAdd ,
nestingDepth - 1 );

listToFill.add( listToAdd );
}
}

}
[/CODE]
 
Zuletzt bearbeitet:
Hier noch eine Lösung mit instanceOf und mit Typsicherheit:
[CODE lang="java" title="NestedCopyVariableNestingDepthGenericsWithInstanceOf"]import java.util.ArrayList;
import java.util.Random;

public class NestedCopyVariableNestingDepthGenericsWithInstanceOf
{
public static <T> ArrayList<T> deepCopy(
final ArrayList<? extends T> listToCopy )
{
final ArrayList<T> result = new ArrayList<>( listToCopy.size() );

for ( final T element : listToCopy )
{
if ( element instanceof ArrayList )
{
@SuppressWarnings("unchecked")
final ArrayList<T> castedElement = (ArrayList<T>) element;

final ArrayList<T> elementCopy =
deepCopy(
castedElement );

@SuppressWarnings("unchecked")
final T castedElementCopy = (T) elementCopy;

result.add( castedElementCopy );
}
else
{
result.add( element );
}

}

return result;
}

public static void main(String[] args)
{
final ArrayList<ArrayList<ArrayList<Long>>> listToCopy = new ArrayList<>( 16 );

fill(
listToCopy ,
3 );

final ArrayList<ArrayList<ArrayList<Long>>> copy =
deepCopy(
listToCopy );

if ( ! listToCopy.equals( copy ) )
{
throw new RuntimeException( "not equal" );
}

System.out.println( "ok" );
}

private static final Random random = new Random();

private static void fill(
// raw type
final ArrayList listToFill ,
final int nestingDepth )
{
if ( nestingDepth < 1 )
{
throw new IllegalArgumentException( "illegal nesting depth " + nestingDepth );
}

if ( nestingDepth == 1 )
{
for ( int i = 0 ; i < 16 ; i++ )
{
listToFill.add( random.nextInt() );
}

return;
}

for ( int i = 0 ; i < 16 ; i++ )
{
// raw type
final ArrayList listToAdd = new ArrayList<>( 16 );

fill(
listToAdd ,
nestingDepth - 1 );

listToFill.add( listToAdd );
}
}

}
[/CODE]
 

Zurück
Oben