r/learnjava • • 5d ago

Building My Custom Data Structure Library Feed-Back pt. 2

A while ago, I posted about a small project I was working on for fun: a Java library for N-dimensional array storage and manipulation.

Originally, I made it for my own game, but eventually decided to put it on GitHub in case anyone else found it useful. I posted here to get feedback, suggestions, and criticism, and I ended up learning quite a bit from the comments.

Since then, I've made several changes, reconsidered some of my original design decisions, and released a new version.

I'd love to get some more feedback: What's good? What's bad? What could be improved? Are there any questions you have about the library or its implementation? I'm open to constructive criticism and suggestions.

I know this kind of library isn't for everyone, and that's perfectly fine. Some people will prefer working directly with Java arrays or existing collections, and I understand that. I'm mainly interested in hearing what you think of the implementation, API, documentation, and overall usefulness.

I'm also interested in feedback on the presentation. I got some comments about the README being hard to read(kinda defeats the purpose, huh?), so I've redesigned it and added more information. Hopefully, that helps.

Anyway, here's the GitHub:

https://github.com/AJ-1-code/JArray

1 Upvotes

21 comments sorted by

•

u/AutoModerator 5d ago

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
  • You include any and all error messages in full - best also formatted as code block
  • You ask clear questions
  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

2

u/8dot30662386292pow2 4d ago

What's bad?

private byte[] bytes;
private short[] shorts;
private int[] ints;
private long[] longs;
private float[] floats;
private double[] doubles;
private char[] chars;
private boolean[] booleans;
private Object[] objects;

0

u/fishybusinessdev 4d ago

whats wrong with it?

1

u/8dot30662386292pow2 4d ago

Where to even use this? You have a single thing that has several arrays for all the different types. What on earth is the use case for this? Why don't you use generics?

1

u/fishybusinessdev 3d ago

That's actually a core part of the design.

JArray supports both homogeneous and heterogeneous data. When storing homogeneous primitive data, it uses the corresponding native primitive array, avoiding the boxing overhead of storing everything in an Object[]. When storing mixed types, it can maintain separate primitive storage alongside the other types.

Generics wouldn't directly accomplish this in Java, since generic types can't be primitive and would still require boxing.

The use case is a general-purpose N-dimensional array that can handle both typed primitive data and heterogeneous data, while retaining efficient primitive storage where possible.

Whether that trade-off is worthwhile is a fair question, but the multiple arrays are intentional, not redundant.

1

u/8dot30662386292pow2 3d ago

Generics wouldn't directly accomplish this in Java, since generic types can't be primitive and would still require boxing.

Require boxing yes, but you can still use primitives if you do it right. I have something like this:

public class Container {
    abstract class Storage {
        abstract <T> T get(int index);
    }
    class IntStorage extends Storage {
        int[] data;

        @Override
        Integer get(int index) {
            return data[index];
        }

    }

    class LongStorage extends Storage {
        long[] data;

        @Override
        Long get(int index) {
            return data[index];
        }

    }

    
    Storage storage;

    int getInt(int index) {
        return storage.get(index);
    }
    
    int getLong(int index) {
        return storage.get(index);
    }

}

1

u/fishybusinessdev 3d ago

I'm not against alternative storage architectures. A Storage hierarchy could be a reasonable approach. But I'm not seeing what specifically makes it better for JArray.

Your example still requires separate primitive backing arrays and specialized storage implementations. It demonstrates another way to organize primitive storage, but doesn't establish that it's simpler, faster, or more maintainable than the current implementation.

Also, your generic get() method returns boxed types like Integer, which means it still involves boxing and unboxing when accessing primitive values through that method.

If you see a specific problem with my architecture, I'd genuinely like to hear it. I'm open to changing things when there's a concrete reason to do so.

1

u/8dot30662386292pow2 3d ago

I guess everyone has the same problem: what is the situation where you need arbitrary amount of arbitrary primitives in a single data structure? I may be too deep in the correct way of doing things that I can't understand what is the situation when this is needed.

1

u/fishybusinessdev 3d ago

I think Python's lists are a good example of why heterogeneous containers can be useful. You can store integers, floats, strings, booleans, and even other lists in the same structure.

JArray offers similar flexibility, but extends it to N-dimensional data, with additional support for native primitive storage when the data is homogeneous.

One of the original reasons I started developing JArray was for my own game. I used it for the map system, where having an N-dimensional structure with operations like slicing and manipulating sections of the map was useful.

Of course, strongly typed structures are preferable in plenty of situations. I'm not suggesting heterogeneous storage should replace them. It's simply another useful way to organize and manipulate data, especially when working with dynamically structured datasets.

1

u/8dot30662386292pow2 3d ago

I think Python's lists are a good example of why heterogeneous containers can be useful.

Thats what I'm asking, why is it useful? I see no usefulness: just because it's possible, it should bot be done. Also you can do exactly same thing in java with arraylist, but you absolute should not.

It's nice that it works for your game though. Still not sure what you are doing that you could not do other ways. It kind of feels like you are missing something important that caused you to create this thing, but I'm still not sure what that might be. Writing your own stuff is always great, don't get me wrong. It's just that I've been teaching so long that I've seen all kinds of things being built when the correct thing is not understood.

Of course, strongly typed structures are preferable in plenty of situations. 

Your thing is also strongly typed, having hererogenous objects does not make typing weak.

1

u/fishybusinessdev 2d ago

I think a spreadsheet-like data grid is a reasonable example of where heterogeneous storage can be useful.

Imagine a grid where some cells contain integers, others contain floating-point values, strings, or booleans. You want to preserve those types while still being able to access the data by coordinates, slice regions, and manipulate the grid as an N-dimensional structure.

You can absolutely store those values in an ArrayList<Object> or an Object[][]. I'm not claiming otherwise. The difference is that JArray provides the N-dimensional array operations and views on top of that storage model.

I also agree that heterogeneous storage shouldn't be used just because it's possible. If the data has a known, fixed structure, a class, record, or strongly typed array is often the better choice. I'm not trying to replace those.

As for why I included heterogeneous storage, JArray is intended to be a general-purpose array abstraction, not exclusively a primitive numerical array library. Supporting mixed values is useful for data whose structure isn't necessarily homogeneous, while homogeneous data can still use native primitive storage.

And you're right that heterogeneous storage doesn't automatically mean weak typing. To be precise, JArray preserves the types of its stored values and provides type-specific accessors, although it doesn't enforce a single compile-time element type through generics.

I'm not arguing that every application needs this. I'm explaining the use case the feature is intended to support.

2

u/desrtfx 4d ago

Check OP's first post

1

u/vegan_antitheist 5d ago

I see that often it actually prevents boxing, the model seems right, the operations seem correct and mostly efficient.

Why do you copy the iterable (which iterates it) just to the iterate over the copy? This seems to make no sense.

which is copied first, so {@code array.addAll(array)} is safe

What is safe when you do a "snapshot" and why would it not be safe?

The class is described as "A dynamically sized, typed, N-dimensional array for Java." but it's not typed. The readme says: "A container that holds different types means Object everywhere."
But then it's Objects everywhere.

Is there no stream api? Why not? a Spliterator with SIZED + SUBSIZED + ORDERED characteristics would let the Stream API parallelise. Why no reduce operations?

JArray of(Object... values) would take an int[] as one value. But of(1,2,3) would box each value and then add it. The javadoc mentions this. But why is it like that? It still takes an array, but there's also fromArray, which is just confusing. What even is a "natural type"? Consider provifing a JArrayFactory, which would also reduce the file size. Now it does so much. Shape management, view algebra, element access, bulk data movement and more.

Is there a fill method that doesn't autobox?

How would one sort the array?

What about add(JArray), mul(double)and similar? Will you add something for "Single instruction, multiple data" (jep 548) when it's actually final?

The method int[] dims() writes something? It modifies dimensions[0]. That seems weird to me. It violates the expectation that a getter is side-effect-free. Lots of methods use it.

get(int index) calls position(int index) and fails if (dimensions.length != 1). A user reading arr.get(5) naturally expects "fifth element" or "flat index 5". If you really want this at least link to getFlat.

toString just creates a giant string. hashCode also just goes over all data. Maybe this is ok. But it might be better to just use fast toString and hashCode but also provide separate methods that go over all data.

toIntArray exists but why not just provide <T> T[] toArray(IntFunction<T[]> arrayFactory) overload that returns T[]? And the usual <T> T[] toArray(T[] a) from Collection too?

slice(int[] starts, int[] ends, int[] steps) seems to be missing

You have slice for N-D but no convenient 1-D shorthand that returns a view (as opposed to copy)?

is tracksSizereallynecessary?

void add(Object value) awlays calls prepareToAdd but the primitive overloads skip it when tracksSize is true.

int indexOf(Object value) calls resolve for each index. The odometer loop in gather is better and if I'm not mistaken that can be done here too.

The Iterator doesn't overrride remove() and so it throws UnsupportedOperationException. But removing something would be possible. removeAt exists.

1

u/fishybusinessdev 4d ago

The snapshot is intentional. It ensures that the source is fully consumed before the destination is modified. This makes self-addition safe, but also handles views or other iterables that may share backing storage with the destination. I agree that it introduces an additional allocation and copy, but I prefer the predictable behavior and simpler implementation over trying to detect every possible form of shared storage.

JArray supports both primitive-specific access (getInt(), setInt(), etc.) and general Object access for heterogeneous data. The latter is why some methods use Objects, but homogeneous primitive storage and typed access are supported.

As for streams, I haven't implemented a Spliterator or Stream API yet. Although, it might be something worth considering, especially for traversal, but parallel streams and reduction operations weren't part of the library's original scope. I'm keeping the focus on storage, dimensions, and views for now.

There is currently a general fill(Object) method. The value is boxed at the API boundary when using a primitive, but the storage layer determines its type once and writes directly to the appropriate primitive storage. It doesn't box each element individually. Primitive-specific fill overloads are something I could consider, but I'd want to establish that they provide a meaningful performance benefit first.

JArray is intended to focus on storage, dimensions, views, and data manipulation, rather than numerical operations. Arithmetic, reductions, and SIMD are interesting possibilities, but they're outside the current scope.(although, also in my github is a small project called NumJ, which does have that, although its incomplete, messy, and broken)

For get() versus getFlat(), I intentionally distinguish coordinate-based access from flat indexing. I can see how that might not be immediately intuitive, though. I will make a note of that in the readme.

The generic toArray() overload and additional slicing conveniences are reasonable suggestions. I'll consider those as well.

Regarding tracksSize and the primitive add() overloads, those are intentional parts of the storage design. The primitive overloads have specialized append paths that avoid unnecessary checks and preserve native primitive storage.

For indexOf(), the odometer traversal suggestion is interesting, and I'll look into whether it can improve performance. The iterator not supporting remove() is also intentional; indexed removal is already available through removeAt().

Thanks for taking the time to go through the implementation.

1

u/8dot30662386292pow2 3d ago

Your documentation says:

NaN equals NaN

This is not true. Nan == Nan is false.

1

u/fishybusinessdev 3d ago

You're correct that NaN == NaN evaluates to false in Java. However, JArray uses Objects.equals() for element comparisons, which delegates to the boxed values' equals() methods.

Double.equals() considers NaN equal to NaN, while distinguishing -0.0 from 0.0. So the documentation describes the equality semantics JArray actually implements, not primitive == semantics.

1

u/8dot30662386292pow2 3d ago

So I'm confused. I am supposed to use this to store doubles as primitives so I don't need to box them. I would expect the primities works as primitives in comparison.

1

u/fishybusinessdev 3d ago

Primitive storage and equality semantics are two separate things. JArray stores doubles in a native double[], and getDouble() returns a primitive double directly, without boxing.

If you specifically want primitive comparison semantics, you can use the primitive accessors:

array.getDouble(0) == array.getDouble(1)

That gives you the normal Java primitive behavior, including NaN == NaN being false and -0.0 == 0.0 being true.

JArray's equals(), contains(), and indexOf() instead use type-sensitive boxed equality semantics. Both behaviors are available; they serve different purposes.

does that make sense?

1

u/8dot30662386292pow2 3d ago

I understand the explanation. I can't see the justification for this design choice.

1

u/fishybusinessdev 2d ago

The justification is consistency with Java's object equality semantics across the different data types JArray supports.

JArray provides primitive accessors for cases where you want primitive operations and comparisons. Its general-purpose equality methods use the equality semantics of the stored values.

I understand that you might prefer primitive comparison semantics for doubles, but that's a different design choice, not necessarily a better one. What specific problem do you see with the current behavior?

2

u/BannockHatesReddit_ 5d ago

This is just a mess 2000 like java files 😭