0

i am trying to code a game from scratch, I have multiple types of buttons, one of those types has to switch the sprites it uses after it gets clicked. all buttons have one set of sprites, but that specific type has an extra field with the second set of sprites.

I have a solution that works, but was trying to us generics to swap the images instead (trying to learn something new). I think i don't understand generics, because the way i did it does nothing.

public class Button {
     protected BufferedImage[] imgs;
}

public class SpecialButton extends Button{

    private BufferedImage[] imgs2;

    public void swapImage() {
        //this works the way it was intended
        BufferedImage[] tmp = imgs;
        imgs = imgs2;
        imgs2 = tmp;
    }
    


    public void swapImageDoesNothing() {
        // this does nothing
        swap(imgs, imgs2);
    }


    public static <T> void swap(T obj1, T obj2){
        T tmp = obj1;
        obj1 = obj2;
        obj2 = tmp;
    }
}

I tried multiple thing, also tried making the swap() method not static, but the goal was to have the static in another Utils class for other classes to use, don't know if i need it anywhere else, but i was trying to learn something about generics

public final class Utilities {

    private Utilities(){}
    
    public static <T> void swap(T obj1, T obj2){
        T tmp = obj1;
        obj1 = obj2;
        obj2 = tmp;
    }
}
  • 1
    This has nothing to do with generics and all to do with the fact that java is pass-by-value, not pass-by reference. – Federico klez Culloca Dec 16 '22 at 13:28
  • 1
    In other words, the moment you do `obj1 = obj2` you're only changing what the variable `obj1` points to, not what it referred to when the `swap` method was called. – Federico klez Culloca Dec 16 '22 at 13:29
  • That is definitely some helpful information, but I am wondering if there is a way to do what I was trying to do, is it possible to pass something by reference in java? Also, why does the Arrays.sort(arr); method change the actual array if its passed by value?? why don't i have to do this arr = Arrays.sort(arr); – Ivo Heberle Dec 16 '22 at 13:36
  • 1
    About `Arrays.sort` is because it changes the array in place, it doesn't create a new one and change the reference of the one you passed in. Assuming for a second that instead of `T` you used a custom `Point` class that has a `x` property in your `swap` method you could do something like `int x = obj1.x; obj1.x = obj2.x; obj2.x = x;` and it would work like you expected. – Federico klez Culloca Dec 16 '22 at 13:40
  • About how to do it I can't think of a way that fits unbounded generics. I'd say do away with generics and use a specific class were you can modify the fields (like the `BufferedImage` in your example) and swap those instaed. – Federico klez Culloca Dec 16 '22 at 13:43
  • 1
    @jhamon I suggest you refresh the page :) – Federico klez Culloca Dec 16 '22 at 13:45

0 Answers0