Don't want to use loops. I tried the below code but it doesn't work for primitive types.
if ( Arrays.asList( myMatrix ).contains( -1 ) )
{
// do something
}
What shall be done here?
You can't avoid iteration in your code since we need some way to test all elements in your array (at least until we will find the one we are looking for). But to make your life easier create some additional utility method like (name could be probably better/more descriptive) public static boolean contains(int[] array, int element) which will handle iteration for us. Then simply use it like if(contains(matrix, -1)).
In Java 8 you could use IntStream which handles int[] myMatrix array correctly (like Array.asList handles Integer[] myMatrix).
So as condition you could use something like:
IntStream.of(myMatrix).anyMatch(i -> i == -1)
Java should really have a method contains on java.util.Arrays.
Commons Lang has it, for example.
So I would either find it in the libraries I already use, or make a static helper method myself (with a simple loop inside).
"I don't want to use loops" -- you can't always get what you want, and in fact in this situation, use a loop.
Related
I have a simple program which processes an M x N matrix. When done processing, I want to print out the matrix to standard output. I'm aware that I can write some method e.g. static [void/String] matrixPrint(int[][] myMatrix) to either print out the matrix or return a String representation of it.
However I'm thinking that a more elegant solution would be to override the toString() method in the Arrays class. That way I could just call System.out.println(myMatrix), which seems to me to be more clear and elegant code than either of the above.
Is there an easy way to do this without creating another class that extends Arrays? Or are there other ways to elegantly print out objects from Java's built-in classes?
You can't override array's toString() (it doesn't implement one). But, you could use Arrays.deepToString(Object[]) which Returns a string representation of the "deep contents" of the specified array. If the array contains other arrays as elements, the string representation contains their contents and so on. This method is designed for converting multidimensional arrays to strings.
That might look like,
System.out.println(Arrays.deepToString(myMatrix));
Short answer is "no".
In order to override a method you need to extend a class. Java does not have a syntax for extending an array, i.e. you cannot write
class MyClass extends String[] { // <<= This will not compile
...
}
However, Arrays class provides a string conversion method that works with arrays of any type. That is the idiomatic way of printing arrays in Java.
The Arrays class has a number of useful utilities for printing arrays. However they rely on you being happy with the default Java format for printing arrays. If you want to do anything specific you will need to write your own methods.
Java 8 streams provide some nice features that you could use without needing explicit iteration. For example:
Arrays.stream(matrix)
.map(row -> Arrays.stream(row).collect(Collectors.joining("\t"))
.forEach(System.out::println);
I have numbers[x][y] and int pm2 = 0;. Is there a way to pass on this Mult-Array onto public static boolean checkNumber(int[] list, int num)? <- the parameters has to be used this way.
I invoked checkNumber(numbers[x][y], pm2);
I need to use the checkNumber method to check if a number has already been entered and returns true if the number is present and false if number is absent.
I am allowed to use multiple methods thought so I did have an idea of doing numbers[x][0] , numbers[x][1] etc, etc and invoking them into multiple checkNumber() methods. I was just wondering if there's a shorter way.
You have single dimensional array as parameter.
So you have to pass one at a time probably in loop.
I was just wondering if there's a shorter way.
No there isn't. The Java language doesn't support any kind of array "slicing", and you can't subvert the type system to allow you to refer use an array with a different type to what it really has.
You need to implement your idea of iterating the int[] component array of the int[][], passing each one to checkNumber(int[], int). Something like this:
for (int[] subarray : numbers) {
checkNumbers(subarray, pm2);
}
This question already has answers here:
How to return multiple values? [duplicate]
(3 answers)
Closed 3 years ago.
This is a small issue, as I could easily whip up a pair class to do the job. I don't really want to do this though, and I feel like there should be some simple, built-in, java-like way of returning two values. What do you guys is the best, simplest way of doing this? Arrays? Some other data structure?
As far as I know, there is unfortunately no built-in representation of a pair in Java (and I certainly wish there was). Personally, when I code a project where I find that a pair class often would be useful, I create a generic Pair<T, U> class (which is probably what you were thinking of). Returning an array is a fast and simple way, but you might come to regret it later, because people who use your method will wonder whether the method might at some point return more than two values.
Whichever solution you choose: whenever you feel that you need a Pair, you should consider whether the time saved today by using e.g. a generic Pair class really is worth the loss of information to the next person who reads the code (and that person may well be you in six months). Writing a separate class for the return type takes more time now, but it would convey more information to those that use your method (namely, it tells the users what the return value represents, and contains useful member names for the two values). If it is a non-public method that is used only a few places, though, a Pair is more acceptable.
Using a container class is the easiest way.
public class Pair<T, U> {
public final T t;
public final U u;
public Pair(T t, U u) {
this.t= t;
this.u= u;
}
}
The closest thing I've seen to a "pair" in the standard libraries are the Map.Entry interface and the AbstractMap.SimpleEntry and AbstractMap.SimpleImmutableEntry classes that implement it.
If both objects are the same class an array is easier to use.
Apache Commons Lang3 provides an abstract Pair class with a couple implementations including ImmutablePair and MutablePair.
Three approaches, all not so great:
Roll your own Pair<A, B>. You said you didn't want to do that.
Return a Object[]. This is not type safe.
Mimic out variables or pointers by supplying single element arrays as parameters.
An example of #3:
public boolean getUserDetails(String userId, String[] lastName, String[] firstName, Date[] dob) {
assert lastName != null && lastName.length == 1;
assert firstName != null && firstName.length == 1;
assert dob != null && dob.length == 1;
...
}
The third option makes life painful for the caller.
So like I said, no nice solution.
As an aside, Scala uses various Tuple classes (up to 21-tuple, from what I remember) to help you with this.
There is a pair class in JavaFX, but you shouldn't use it. What you SHOULD use is something like this:
// We've skipped imports and package declarations
public final class YourClass {
/* Assume there is a bunch of stuff here */
// I don't know what method you're using, so forgive the silly example
public YourClass.Pair sillyExampleOfPairs(String someString) {
return new YourClass.Pair(someString, someString.length() * 13);
}
#Value // Lombok annotation.
public static class Pair {
String text;
int integer;
}
// this is an even more succinct possibility
#Value public static final class ShorterPair {String text; int integer}
}
While the name Pair here is obviously not that well chosen, and you should choose a more descriptive name, the obvious ways this will work (the fields are final private and you have a getter on each, because of the annotation), should not be lost on you. And while yes, this is slightly more wordy than using Pair, it's much more robust. What if you do need to add an extra parameter to the return value? You "only" need to change this class then. And you can update all the relevant JavaDocs immediately, which is also nice. If you have to change types, they would both entail similar amounts of work.
As long as you're only adding stuff, the old getText() and getInteger() methods would keep working as they did before. You also avoid having to add Yet Another Dependency to your projects. It's not a big win. Having Pair available is nice for prototyping, but it's not nice for later.
My final theoretical CS-y argument is that Pair is the same type as Pair. But if you have a Phonebook.Entry (with String and int) and say, Inventory.Item (with a name and a number of items we currently have inventoried), these two are very distinct types, which do very distinct things. You can't put one into the other. This is a Good Thing.
It's also much clearer for us poor bastards that have to go and debug your systems to see something like "com.name.project.something.something.Phonebook.Entry" in a stack trace than "org.apache.commons.lang3.tuple.Pair". One of these tells me WHAT I'm supposed to be looking at, and gives me some info on WHY I'm seeing a pair. The other says... nothing.
Now you might not care that you have to type for 3 extra seconds to save me 3 minutes. But I choose to believe in the goodness of your heart, and the nobility of your soul. Therefore, do the right thing.
Write a small static class instead.
I have been told by experts that when faced with the question of pairs, one of two things is true:
You need to rethink your structure (this blunt answer doesn't help anyone)
You need to build your own class to hold the pair
I would suggest that the second case is not all that abnormal. However, if what you are doing seems too trivial for introducing a new class, then using a Map could work, as others have suggested. If you are simply sending a single response back, then a Map seems like a bit much.
If a list of pairs sounds like it would work, and you need to maintain order, you could try a LinkedHashMap so that order is maintained.
if both are integers then I would advise a java.awt.Point but otherwise just create a container class with two objects x and y
Some observation of mine:
Array is bulit-in, fast and easy to use, although imposible to expand its capacity. What if you want 3 values to be returned after 3 months?
ArrayList/other colletions can be good, allows you to increment the capacity(initially 10).
Note that Vector can be overkill in comparison to ArrayList when you only want to store 2 values to be fetched later. Map also can be good because it's always sorted and ordered.
Some user-defined class: maybe an option if is meaningful(means that the data returned is important-ish to be a Java Bean), and you want to store more than just 2 integers into it. Readibility is better in case you add more notes in its Javadoc. Can be expanded as you like, just add fields in this class. Slower, but safer.
This question already has answers here:
How do I determine whether an array contains a particular value in Java?
(30 answers)
Closed 5 years ago.
I want to know if there's a way of doing something like this in Java :
if(word in stringArray) {
...
}
I know I can make a function for this but I just want to know if Java has already something for this.
Thank you!
There are many collections that will let you do something similar to that. For example:
With Strings:
String s = "I can has cheezeburger?";
boolean hasCheese = s.contains("cheeze");
or with Collections:
List<String> listOfStrings = new ArrayList<String>();
boolean hasString = listOfStrings.contains(something);
However, there is no similar construct for a simple String[].
In SQL
x in ('Alice', 'Bob', 'Carol')
In Java:
Arrays.asList("Alice", "Bob", "Carol").contains(x)
The Java language is designed to be powerful but also simple. There is no such operator in Java at the language level, but certainly libraries have been written to facilitate such queries.
If you want to know if some object is a member of some set of objects, then instead of an array, you should use -- what else? -- a Set. These data structures naturally allows such queries, and better yet, they're optimized for such queries.
You can easily check if a given string is in a Set<String> like this:
String[] arr = { "Alice", "Bob", "Carol" };
Set<String> names = new HashSet<String>(Arrays.asList(arr));
System.out.println(names.contains("Alice")); // true
System.out.println(names.contains("Dean")); // false
Using a HashSet, contains is a constant-time operation. This is much better than a linear search through an array.
You should familiarize yourself with what data structures are made available for you by the Java Collections Framework. They allow you to write codes that are idiomatic, maintainable, flexible, and supported by many of the powerful algorithms available for these data structures.
See also
Java Tutorials/Collections Framework
List<E>, Set<E>, Queue<E>, Map<K,V>, SortedMap<K,V>, NavigableSet<E>, etc.
Effective Java 2nd Edition, Item 25: Prefer lists to arrays
Java has no "in" operator.
For arrays you need to iterate them and look for a matching item.
For Lists you can use the contains method.
You can use java.util.Collection.contains() for collections. If what you have is a non-null array, you can use java.util.Arrays.asList(array).contains().
tabs[j].indexOf("lelamondeestgrand...")!=0
Without arrays:
public static <T> boolean in(T value, T... list) {
for (T item : list) {
if (value.equals(item))
return true;
}
return false;
}
usage:
int val = 1;
assert in(val, 1,2,3,4);
if(myArrayList.contains("hello"))
{
// yay
}
It first depends what the array is an array of. If it is an array of the exact words you can convert it to a regular collection and use the contains() method. If it is an array of sentences or phrases etc. you must iterate over it to tell.
The most general solution that will catch all these is to iterate as follows.
for(String s : stringArray)
{
if(s.indexOf(word) > 0) return true;
}
return false;
This looks at every string in the array, and checks to see if the word is contained anywhere within it. It will return true after the first occurrance is found.
If the array is sorted, you can use Arrays.binarySearch to find the data.
Like this:
if (Arrays.binarySearch(stringArray, word)>=0) {
// word found in the array.
}
If the array is unsorted, commons lang, has the ArrayUtils.indexOf method.
Finally, if you are searching a large array, then a parallel search may be worthwhile using ParallelArray, from JSR166 - coming in Java SE 7 and available now as a download. This article gives an introduction.
give us more details on what your problem looks like, and what you need to check. There are several different ways to do stuff like this. If you need to keep asking if item A is in set B.. make set B a HashSet, and you can call contains very quick. You can get the same effect in several java-ish ways, but they will vary depending on your data etc.
In C+ one can use iterators for writing to a sequence. Simplest example would be:
vector<int> v;
for (vector<int>::iterator it = v.begin(); it!=v.end(); ++it) {
*it = 42;
}
I need something more complicated - keep iterator as a class member for a later use.
But I don't know how to get this behavior from Java iterators.
Are there writable iterators in Java at all?
If not then what replaces them?
The ListIterator (which you can obtain by List#listIterator()) has add() and set() methods which allows you to respectively insert and replace the item at the currently iterated index. That's as far the only "writable iterator" as I can think of in Java.
Not sure though if that is the exact replacement of the given C++ code since I don't know C++.
As arrays can be accessed directly and quickly by their index, you don't really need an iterator object. Wouldn't it be enought to save the index of the array in that class member? This would permit to read and write the value of the array.
PS: You could use an ArrayList, which is an automatically growing set of arrays and use the ListIterator as Balus described in order to use the iterator-object-approach.
Looks more like you want a List (or maybe some other collection, like Set) or an array.
Also, you could just make your contents mutable. It looks silly for integers, but continuing your example
for (MutableInteger i : CollectionOfMInts) i.setTo(42);