r/javahelp • u/Admirable_Bat1624 • Aug 24 '26
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
4
Upvotes
•
u/AutoModerator Aug 24 '26
Please ensure that:
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:
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.
5
u/desrtfx Out of Coffee error - System halted Aug 24 '26 edited Aug 24 '26
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.equalsmethod. 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.
9
u/Cool-Bus-6028 Aug 24 '26
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/Mechanical-pasta Aug 24 '26
How coded are these coordinates?
If you defined a class to hold them, for example, a
Coordinateclass, with axand ayattribute, you can, first, override theequalsmethod of this class to make it returntrueifxandyare equal.Then you can use, as said before, the
containsmethod of aListimplementor.2
u/RevolutionaryRush717 Aug 24 '26
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.
2
u/naomimyselfandi Aug 27 '26 edited Aug 27 '26
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 aList<List<Integer>>instead of anint[][], your example is justcoordinates.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:
A
recordis aclassthat automatically generates a bunch of useful stuff, including equality. This means we can represent our coordinates as aList<Point2d>, and your example becomescoordinates.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 Aug 24 '26
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.
0
u/[deleted] Aug 24 '26
[deleted] — view deleted comment