r/learnjava • • 1d 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

0 Upvotes

12 comments sorted by

•

u/AutoModerator 1d 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 1d 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 1d ago

whats wrong with it?

1

u/8dot30662386292pow2 1d 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 14h 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 10h 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/vegan_antitheist 1d 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 1d 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 9h ago

Your documentation says:

NaN equals NaN

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

1

u/fishybusinessdev 3h 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.

2

u/BannockHatesReddit_ 1d ago

This is just a mess 2000 like java files 😭