I am solving an assignment where I should not use arrays or collections to sort Integers. I am doing it with strings. I want to know whether strings in java are stored as character array.
Use LinkedList where implementation is not backed by an array.
Yes String does use char array behind the scene
While some are saying to check the Java source, I'll save you some time.
I can guarantee that even starting the JVM uses a collection in some way. That is how fundamental they are to programming. So I'm assuming your assignment takes that into account. Therefore, in this case, I would say for these, your professor means to not explicitly use a collection or array. Avoiding behind the scenes collections is literally impossible.
Don't believe me? Take a look at this code:
public static void main(String [] args) {
// looks like an array to me ^
}
Do note that the String class in Java has a toCharArray() method, so avoid this.
Related
I'm using a class that has a method that accepts a boolean[].
This code does not raise any errors
public class myclass{
void move(boolean[] myarray) {
//Do stufff
}
}
Now, I do a little C++ coding, and this would not work in the context of dynamic memory.
So this is essentially a java question:
In my case the array being received has a known length, but I want to know how you would handle this in Java if it is dynamic (as well as what I should do if its not dynamic).
I'm guessing the compiler or JVM is going to handle this, but I want to know the speed optimizations I can implement.
Arrays in Java are always constant length. From The Java Tutorials, "The length of an array is established when the array is created."
If you wanted dynamic arrays, you'd use something from the Collections Framework, e.g. ArrayList.
In any case, a reference to the array (or collection) is passed into move(...), so there shouldn't be any difference in speed just for the function call.
When using the array, I'd expect (static) arrays to be dereferenced more quickly than going through the function calls to access elements of (dynamic) collections. However, to have a proper comparison, you'd need to provide more context of how your array is used.
You should consider using ArrayList<>() for all your needs related to iterating arbitrary length collections.
Also using List is a good practice in the Java world. There is a article about programmers who use Lists and arrays and those who use lists tend to produce less bugs.
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 want to get some views on the behavior of the following program :
package main;
import java.util.Arrays;
public class StringAnagram {
public static void main(String args[]) {
String a = "aabbaabb";
char[] aArr = a.toCharArray();
Arrays.sort(aArr); //1
Arrays.sort(a.toCharArray()); //2
System.out.println(aArr); // Sorted
System.out.println(a.toCharArray()); // UnSorted
}
}
According to me statement 1 sorts the character array referenced by aArr but when it comes to statement 2 the sorting of character array is taking place but somehow the sorted array is not referenced by any variable, so the behavior is lost. Could someone please help me with the same.
Yes. You are right.
Each call to toCharArray() actually creates a new array instance with the characters in the string.
In the case of aArr, you actually refer to the new array instance, you use aArr to sort. Its the array instances referred by the variable aArr which gets sorted.
But when you pass a.toCharArray() to Array.sort() method, you are passing array instance which you don't have a variable referring to. The array instance gets sorted but you don't have any reference.
When you you call println using a.toCharArray() again a new array instance is created and passed to println which is obviously unsorted.
Well, let's see what happens.
First, a.toCharArray() is called. This returns a new char array containing the chars "aabbaabb".
Then, this array is sorted.
You didn't give yourself a way to access the array, so you can't. This is what "lost" means here. Nothing special or magic happened, you just made an array you can't access. It's not going to waste memory - the garbage collector will detect that it can't be accessed, and destroy it.
It's similar to if you just did this without the sorting:
a.toCharArray();
Again, toCharArray goes and makes an array for you, and you don't give yourself a way to use it, so it's also "lost". The sorting was a red herring.
Arrays.sort(a.toCharArray());
This sorts the array returned by a.toCharArray() and not the String a. So whenever you do a.toCharArray() you get a separate(new) Character array of the String. Hence it is unsorted.
I am a student who has just shifted from C++ to Java.
In Java what could be the main reason for defining separate data types for Strings and Char arrays? What is the difference between the two?
Since I have only studied C++, up till now I was under the impression that they are the same thing. Please clarify if possible.
String is immutable. Char array is not. A string is implemented with a char array underneath but every time you try to modify it (like with concatenation, replace etc.) it gives you a new String object.
So, String behaves as a constant Char array but comes with certain syntactic sugar that also makes them very easier to use. For example, the addition + operator has been overloaded as a string concatenation operator as well.
In Java, String is a basic system class that essentially wraps a char[]. There are several reasons why, for most uses, having a full class is preferable to directly handling arrays:
Strings are immutable; once you have a reference to some String, you know it's never going to change.
Strings provide useful methods that a bare array couldn't, such as length(), and have clearly-defined comparison semantics.
You never have to deal with string termination yourself.
Java has a special exception for the rule of "no operator overloading" to support string concatenation (with +).
Essentially, it's good OO practice to use a class to collect the desired behavior and the data structures in the same place, and String wraps up an array of characters with the useful operations that you want to perform on a string.
String is a class in Java and offers you methods and is also an Object.
A String-object is also immutable.
Internal the value is a char-array.
There is a semantic difference. Just because data is stored the same way, this doesn't mean it's the same thing. Dates and Amounts may also have the same internal representation (long for a timestamp or fixed point amount of cash), but they're not the same. The char array could as well mean a 16-bit image.
In object orientation, it's good practice to model objects based on what they are and can, and not by how they internally store their data. This allows you to encapsulate the data (and restrict or control (observer support) access with getters/setters, or even make the internal representation immutable or poolable), and provide appropriate methods for your objects.
String is immutable in Java and stored in the String pool. Once it is created it stays in the pool until garbage collected.Since, String is immutable , the logging password is as readable string.It has greater risk of producing the memory dump to find the password.
where as Char array is created in heap and you can override with some dummy values.
The advantage to using the string object is all the methods available to it.
For example:
stringExample1.equals(stringExample2);
String stringExample3 = stringExample1.replace(substring1, substring2);
It seems to me like ArrayList would be easier to use in nearly every scenario, it being very versatile. Is there an instance where a String[] would be used to store inputted data? If there is such a case, there must be a drawback in ArrayList, what would that be?
Only thing that comes to mind off the top of my head would be the variety of String methods like, substring() and split(), etc.
EDIT: New to StackOverflow as well. I apologize if this was a re-post. And thanks for the formatting.
The short answer is: don't use an array, always use an array list. The only exception to this is if you absolutely need to control the amount of memory used or you have some specific performance constraint that only String[] can support.
In general, though, arrays are terrible to work with in an object oriented language, and almost always for the same reason: they make it very easy to break encapsulation. For example:
public class ExampleArray {
private final String[] strings;
public ExampleArray(String... strings) { this.strings = strings; }
public String[] getStrings() { return strings; }
}
See any problems? Yea, you need to write getStrings() like this:
// ...
public String[] getStrings() { return Arrays.copy(strings); }
// ...
Otherwise, some caller can get a hold of your class' internal data and start modifying it. The only way to prevent this is to copy it every time a caller wants to see it. As opposed to the right way:
public class ExampleList {
private final List<String> strings;
// ...
public List<String> getStrings() { return Collections.unmodifiableList(strings); }
}
Now you're not copying the data, you're just sticking it behind an API that doesn't allow changes. If you use the Guava Immutable* classes, even better.
Of course there are situations where you want to use String[] instead. If you know in advance how long the list will be, for instance, and the list might be large.
The main disadvantage of using ArrayList is that as the list grows, the array has to be reallocated, which isn't a free operation. You can mitigate that by preallocating it to be the size (or larger) you expect using the constructor that accepts an initialCapacity.
ArrayList is dynamic grow-able array in size, Where as string array or any type of array is static in size.
Obviously this dynamic grow features cause some cost, it reallocate the array with new size and copy element to it.
You can initialize Java arrays at compile time, like:
String data[] = { "a", "b", "c" };
In old versions of Java there was also the case for type safety. ArrayList elements had to be casted to the original type whereas Java arrays where type safe.
Java arrays are part of the language and you will not be able to change them. ArrayList is part of the Java API. If you need (I do not recommend it though) you could substitute your own library to implement the ArrayList job.
Check out these questions asked by others in stackoverflow:
Array or List in Java. Which is faster?
Java Performance - ArrayLists versus Arrays for lots of fast reads
The only case that comes to my mind when array is used to hold some values is when there's a method taking variable number of arguments like:
void doSth(int i, String... strings){
if(strings.length>0){
//some stuff
}
Otherwise I hardly ever intentionally create a situation, when array needs to be used.