Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (481)
Games in Android Showcase (110)
games submitted by our members
Games in WIP (547)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Instantiating Generic Arrays  (Read 2878 times)
0 Members and 1 Guest are viewing this topic.
Offline ClickerMonkey

JGO Coder


Medals: 20


Game Engineer


« Posted 2013-02-09 03:52:34 »

Greetings Earthlings!

So something that has always bothered me is the outrageous things you need to do to instantiate a generic array (perhaps I'm overreacting).

There are two methods presented EVERYWHERE:

1  
2  
3  
4  
5  
6  
public <T> T[] alloc(Class<T> type, int length) {
   return (T[])Array.newInstance(type, length);
}
public <T> T[] alloc(int length) {
   return (T[])new Object[length]; //eww, doesn't always work
}


The first way sucks, you need to pass in the class type, which means whatever you have creating the array a user needs to pass in the class type... unnecessary code I daresay!

The second way sucks as well, doesn't work for me always, it's annoying. Especially in this case:
1  
2  
3  
4  
5  
6  
public class Foo<X extends Bar> {
  public X[] bars;
  public Foo(int length) {
    bars = (X[])new Object[length];
  }
}


NOPE, doesn't work... since X is at least type Bar, you need to do this:

1  
2  
3  
4  
5  
6  
public class Foo<X extends Bar> {
  public X[] bars;
  public Foo(int length) {
    bars = (X[])new Bar[length];
  }
}


Hey that works! Except you still have warnings... I don't like warnings, hence why I think both of these options suck.

So yesterday an alternative method POPPED in my head... something that is so simple, there's no casting, nothing ugly...

Somehow I haven't found ONE website or code example where someone does this, I feel like a god damn explorer (perhaps of the DORA quality).

1  
2  
3  
4  
5  
public class ArrayUtil {
public static <T> T[] alloc(int length, T ... base) {
  return Arrays.copyOf( base, length );
}
}


Boom. It's simple and can even be used in two different ways:

1  
2  
String[] x = ArrayUtil.alloc(4);
String[] y = ArrayUtil.alloc(4, "first", "second");


You know how much ugly code exists in sooo many common libraries that require you to pass in Class<T> so it can create an array? I say they get rid of that silliness.

What say you?

Offline ra4king

JGO Kernel


Medals: 345
Projects: 2
Exp: 5 years


I'm the King!


« Reply #1 - Posted 2013-02-09 08:01:03 »

You are a goddamn genius ClickerMonkey. I've always wanted to get rid of those warnings. Here, eat my medal.

EDIT: Blegh Eclipse now gives a new stupid warning on the "T ... base": "Potential heap pollution via varargs parameter data" -___-

Offline Roquen
« Reply #2 - Posted 2013-02-09 08:16:09 »

Like I've always said: type erasure sucks.
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Danny02
« Reply #3 - Posted 2013-02-09 08:49:43 »

I actually like type erasure. Compared to how C# handles generics.

ps: nice hack, have to take a look at it

update:
sry but your new method does not work.

the var args trick don't work in your Foo<X extends Bar> example, you will get a cast exception.
so it seems the old casting an array to the anyway erased generic is the best.

I really don't know why you have a problem with creating a Bar array, it just a simple thing to know.

1  
2  
3  
4  
5  
6  
7  
8  
9  
class Foo<T extends Bar>
{
  Foo()
  {
    T[] a = alloc(2);//throws exception
   T b = null;
    T[] c = alloc(3, b);//will work but is strange
 }
}
Offline Spasi
« Reply #4 - Posted 2013-02-09 10:16:25 »

EDIT: Blegh Eclipse now gives a new stupid warning on the "T ... base": "Potential heap pollution via varargs parameter data" -___-

You can get rid of that warning with @SafeVarargs on the alloc method. Requires Java 7+.

1  
2  
3  
4  
5  
6  
7  
8  
9  
class Foo<T extends Bar>
{
  Foo()
  {
    T[] a = alloc(2);//throws exception
   T b = null;
    T[] c = alloc(3, b);//will work but is strange
 }
}

Actually it's the second call that throws a NPE. The first one works fine. I tested the wrong code.
Offline Danny02
« Reply #5 - Posted 2013-02-09 10:40:13 »

Actually it's the second call that throws a NPE. The first one works fine.

why should it throw a NPE, it will just create "new T[]{null}", I'm running java7 btw.

here the test app I use:
http://pastebin.com/WQNJmi2e

which gives me the following results:
1  
2  
test1 fail
test2 win


when you remove "extends Number" both methods work.


ps: I still think casting an array of the generic base class is just the easiest, shortest and performant option
Online tberthel
« Reply #6 - Posted 2013-02-09 10:53:26 »

Dynamic languages at run time do not need templates.  Everything is an Object.  Templates for Dynamic languages are for noobs.

Offline Spasi
« Reply #7 - Posted 2013-02-09 10:57:56 »

why should it throw a NPE, it will just create "new T[]{null}", I'm running java7 btw.

Sorry about that, I used T[] b (instead of T b) when I tested.

here the test app I use:
http://pastebin.com/WQNJmi2e

which gives me the following results:
1  
2  
test1 fail
test2 win

Indeed, the first test fails on JDK 7, but works fine on JDK 8. Will try to find if there's been a bugfix in 8 related to that.

Edit: Seems like a javac fix. Compilation output for test1:

1  
2  
3  
4  
// JDK 7
Number[] a = (Number[])alloc(3, new Object[0]);
// JDK 8
Number[] a = (Number[])alloc(3, new Number[0]);
Offline Danny02
« Reply #8 - Posted 2013-02-09 11:15:23 »

seems like the java 7 type inference can't decide on the type.

did some more tests, when one removes the static from the "alloc" method and replaces the method generic with the class generic everything works.
Offline Roquen
« Reply #9 - Posted 2013-02-09 17:40:55 »

I actually like type erasure. Compared to how C# handles generics.
It's fine if you're not using it for anything beyond AOT type checking...beyond that: it sucks.
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Best Username Ever

Junior Member





« Reply #10 - Posted 2013-02-09 18:38:56 »

I actually like type erasure. Compared to how C# handles generics.

What is the benefit of type erasure? Would someone designing a language from scratch decide to include it? I thought it was just a hack to maintain backwards compatibility.

Dynamic languages at run time do not need templates.  Everything is an Object.  Templates for Dynamic languages are for noobs.

Machine code does not need types. Everything is a byte. Type declarations and variable declarations are for noobs.
Offline Roquen
« Reply #11 - Posted 2013-02-09 20:01:51 »

Machine code is strictly typed.  The base types are unions, but it still typed.  From a certain point of view what you're saying isn't incorrect, but by the same kind of logic C is the ultimate language.
Offline Best Username Ever

Junior Member





« Reply #12 - Posted 2013-02-09 20:31:39 »

I am aware of the technical correctness but logical absurdity. Smiley (Technically I said type declarations and I would argue the definition of type.) I do not agree that assembly or dynamic languages or C take away the need of certain language features.

Dynamic languages and assembly language share something in common. They are perfectly fine if you develop code by entering one key at a time from start to finish with no breaks and no mistakes, but if you ever want to rewrite portions of the program, port it to a different platform, incorporate another person's code, or happen to be a mortal, then their practical utility is greatly diminished.
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

atombrot (25 views)
2014-08-19 09:29:53

Tekkerue (24 views)
2014-08-16 06:45:27

Tekkerue (23 views)
2014-08-16 06:22:17

Tekkerue (13 views)
2014-08-16 06:20:21

Tekkerue (20 views)
2014-08-16 06:12:11

Rayexar (58 views)
2014-08-11 02:49:23

BurntPizza (38 views)
2014-08-09 21:09:32

BurntPizza (30 views)
2014-08-08 02:01:56

Norakomi (37 views)
2014-08-06 19:49:38

BurntPizza (67 views)
2014-08-03 02:57:17
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!