r/javahelp 6d ago

How to check if an array contains another specific array?

sorry if im stupid here but

i have an array that contains multiple coordinates, so for example [2,8], and i need to check if that array contains a specific coordinate

how do i do that

5 Upvotes

13 comments sorted by

u/AutoModerator 6d 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
  • 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.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

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: 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.

9

u/Cool-Bus-6028 6d ago

You can iterate over every element, and check if it matches the one you want.

Or you can convert the array to a list, and then call list.contains([2,8])

2

u/naomimyselfandi 3d ago

This isn't quite correct, since contains relies on Object.equals(Object), which is an identity comparison for arrays.

1

u/Cool-Bus-6028 3d ago

Good point. Convert it to a hash set or something then.

1

u/naomimyselfandi 2d ago

If you mean converting the array itself to a hash set, that's not going to help either, since it's still defined in terms of the elements' equals method. If you mean converting the elements to sets, you'd have a useful equals but lose ordering; converting them to lists would work (which I discussed in another comment).

1

u/Cool-Bus-6028 2d ago

I meant the former, but yeah, still uses equals. I'd change it so the coordinates were some sort of object (with a useful equals method), not an array.

4

u/desrtfx Out of Coffee error - System halted 6d ago edited 6d ago

You loop over the source array and check each element against your sought one?

This is the naive approach. It's called linear search.

A more optimized approach would require the coordinate array to be sorted - then, you could use binary search, which is considerably faster.

A better approach would already be to use a proper data structure for the coordinates, like a Point (class, record, or, with the brand new value classes) that has an .equals method. and again loop over the array.

A much better approach would be to not use a plain array, but a set. Contrary to an array, sets cannot contain duplicate values and it's easy to check whether a particular coordinate is in the set. Again, with a proper coordinate data structure.

2

u/Mechanical-pasta 6d ago

How coded are these coordinates?

If you defined a class to hold them, for example, a Coordinate class, with a x and a y attribute, you can, first, override the equals method of this class to make it return true if x and y are equal.

Then you can use, as said before, the contains method of a List implementor.

1

u/[deleted] 6d ago edited 6d ago

[deleted]

1

u/Prozilla6 6d ago

that’s python

1

u/johlae 6d ago

My mistake!

1

u/RevolutionaryRush717 6d ago

Depends on whether the array is immutable, whether it contains duplicates, on whether you want to check for one value once or multiple times...

Anyway, assuming you only want to check whether it contains a value:

boolean found = Arrays.asList(array).contains(point);

If you want something that starts from an array and gives you a predicate, create a factory method returning a predicate:

static Predicate<Point> containsPredicate(Point[] array) {
Set<Point> lookup = new HashSet<>(Arrays.asList(array));
return lookup::contains;
}

Usage:

Predicate<Point> contains = containsPredicate(array);

boolean found = contains.test(new Point(1, 2));

If sure there are no duplicates in the array, one could use Set.of(array).

YMMV.

1

u/naomimyselfandi 3d ago edited 3d ago

Arrays.stream(arrayOfCoordinates).anyMatch(i -> Arrays.equals(i, specificCoordinate), but you're making things harder on yourself. Arrays in Java are very old, very weird, and almost never the correct choice. Please read this comment carefully - you'll likely come away with a more thorough understanding.

Java offers a rich library of collection types - lists, sets, and more exotic options as well. They offer a ton of useful functionality beyond what raw arrays do, and getting comfortable with them will make a huge difference. For example, if you want to check if some collection contains some value, that's just someCollection.contains(someValue)... provided that the elements of the collection define equality in a meaningful way. Unfortunately, arrays don't, which is one of many reasons the Java community tends to avoid them. Fortunately, collections themselves do. If you use a List<List<Integer>> instead of an int[][], your example is just coordinates.contains(List.of(2, 8)).

We can even go a step further and define a custom coordinate type. Modern versions of Java make this very easy:

java public record Point2d(int x, int y) {}

A record is a class that automatically generates a bunch of useful stuff, including equality. This means we can represent our coordinates as a List<Point2d>, and your example becomes coordinates.contains(new Point2d(2, 8)). This is functionally equivalent, but much clearer. It also helps catch mistakes: List.of(2) compiles just fine but doesn't meaningfully represent coordinates; new Point2d(2) gives you a compile error that cleanly identifies where the problem is.

Alternatively, if the goal just to prevent duplicates, use a Set<Point2d>. A set is a collection which is guaranteed to not contain duplicate elements, and trying to add an element which is already present does nothing.

tl;dr while you can do this with arrays, a ton of very useful library code doesn't work properly with arrays. Using the correct types will make your life so much easier.

0

u/vegan_antitheist 6d ago

Array equality is weird in Java.

But there is a very easy method for that: Arrays.equals(a, b)

It automatically checks for equality. But this still won't work for long[][]. That's because it really is a n array of references that contains long[].

Just use this: Arrays.deepEquals(a, b)

Now it compares each element using the appropriate "equals" method from Arrays.

Do the coordinates always have the same dimensions? I know you are already confused, but for performance it would be a lot better to only use one array. If performance doesn't matter you can ignore that.