Array as an attribute in a java class? - java

I have an assignment which consists of several small tasks:
I have to initilize an array and fill it with a 200/400/800 values (each amount - once).
I have to take the array values and put it in a red black tree, with certain conditions that are translated to methods.
Some more tasks.
I could do it all in the main class, however it seems to me I would be better off start a new class - handleArray.
If I start a class such as:
public class handlyArray{
protected int [] arr = new int[];
}
But if I do that, should I write a "get" and "set" functions to get the array's length?
The problem is that when I make this an error pops up - "Array initilizer expected".
Additional functions I have in the class:
public void fillArray(handleArray arr, int k){
Random rand=new Random();
for (int i = 0; i <k ; i++) {
int value = rand.nextInt(1024);
arr[i]=value;
}
}
- A function that creates Nodes for the redblackTree and inserts them to the tree
Any suggestions for how to build it?
Can I build the class with no attributes at all?
Thanks!

I'm wary of this being homework so I'll give you an overview and let you do the specifics.
Yes you can build a getter and setter in your new class, something like:
public int[] getArray() {
return arr;
}
public void setArray(int[] arr) {
this.arr = arr; //
}
As for getting the length, you don't need a method for it as you can just call the above getter and ask it for the length, e.g.
int arrayLength = handlyArray.getArray().length;
Finally yes you need to set up your array first, if you pass in an initialized array to the setter that will do fine, e.g.
handlyArray.setArray(new int[] {200, 400, 800});
Good luck, feel free to ask if you require further explanation.

You can inisialize the array inside the method like this :
public void fillArray(handlyArray arr, int k) {
Random rand = new Random();
arr.arr = new int[k];//<<---------------------Initialize the array
for (int i = 0; i < k; i++) {
int value = rand.nextInt(1024);
arr.arr[i] = value;// Note to fill the array you have to use arr.arr not just arr
}
}
and the handlyArray should be like this :
public class handlyArray {
protected int[] arr;//<<---------------------Just declare the array
}
to use fillArray method you can use :
a.fillArray(new handlyArray(), length);

I don't think so. I would just do a static method somewhere:
public static int[] randomArray(int size){
Random rand=new Random();
int[] arr = new int[size];
for (int i = 0; i < size ; i++) {
int value = rand.nextInt(1024);
arr[i]=value;
}
return arr;
}
Now, as for the red/black tree, I believe that a TreeSet is implemented with a red/black tree.

You can't set an arrays length. The length of an array has to be set during initialization. You can pass the length of the array in the constructor of your class:
public class HandleArray {
protected int [] arr;
public HandleArray(int length) {
arr = new int[length];
}
}

Related

How would I add, delete or insert arrays in Java using static methods (no ArrayLists)

I am trying to self-learn Java, and have an issue with these arrays I have to make without ArrayLists. I tried to look online on static methods, but I can't find anything that could help me understand. I have to make 3 methods that can be used to modify arrays. So, for adding a value to the end of an array, the method should have the array and the value as parameters. It should then return a new array which is the same as the old array but with the added on value. The site I'm trying to learn this on shows me the block of code and explains what methods do, but it doesn't show me how to use them.
public class Arrays {
static void array() {
System.out.print("1, 2, 4, 7");
}
static void add() {
System.out.print(", 11");
}
public static void main(String[] args) {
System.out.println("Array:");
array();
System.out.println(" ");
System.out.println("Array with Added End:");
array();
add();
System.out.println(" ");
}
}
...for adding a value to the end of an array, the method should have the array and the value as parameters. It should then return a new array which is the same as the old array but with the added on value.
I'm going to assume that add is the method that will add something to your array and that your array is of type int[]. I'll build the method step-by-step:
method should have the array and the value as parameters
add(int[] arr, int val) {}
It should then return a new array which is the same as the old array
The return type of the method must therefore be the same as the array parameter arr. Since you stated the method must be static:
public static int[] add(int[] arr, int val)
{
// todo: make this work
}
It should then return a new array which is the same as the old array but with the added on value.
Arrays cannot be resized so you need to create a new array (which is also specified in the instructions) that is large enough to hold all the elements of arr plus one additional element. There are several ways to populate your new array:
Copying each element yourself:
public static int[] add(int[] arr, int val)
{
int[] newArray = new int[arr.length + 1];
for (int index = 0; index < arr.length; index++)
{
newArray[index] = arr[index];
}
// Arrays start at index 0 so arr.length will be the last
// position in newArray.
newArray[arr.length] = val;
return newArray;
}
Using java.util.Arrays:
public static int[] add(int[] arr, int val)
{
int[] newArray = Arrays.copyOf(arr, arr.length + 1);
newArray[arr.length] = val;
return newArray;
}
Using System.arraycopy:
public static int[] add(int[] arr, int val)
{
int[] newArray = new int[arr.length + 1];
System.arraycopy(arr, 0, newArray, 0, arr.length);
newArray[arr.length] = val;
return newArray;
}
This should be enough of an example on working with arrays to help you write the other two methods.

How to get length from array as a cass memeber?

I have a class that has some arrays as members. In some member functions i want to then iterate over said arrays. But when i try to get the length of the array i see the error non static variable cannot be referenced from a static context.
I have the line for(int i = 0; i < this.blue; i++){} and the array is private int[][] blue;
For example:
public class M{
private int[][] arr;
public static void func(){
for(int i = 0; i < this.arr.length; i++){
// ^^^^ compiler does not like this
}
}
}
I understand that i am not looking at an instance of the class, so the value could be anything, but then how will i ever be able to preform such basic operations if i have to know everything before hand?
I have tried to create another member that holds the dimensions, but that leads to the same issue.
public class M{
private int[][] arr;
public void func(){
for(int i = 0; i < this.arr.length; i++){
// ^^^^ compiler does not like this
}
}
}
This removes the error. That is removing static from func(). At some point I learned to write it and then stopped questioning it. Thanks for the input in the comments.

How to reset a sorted array to unsorted in Java?

I am writing a program to compare different sort methods. I random generated 100,000 integers and store these data to an array. I want to apply the same array to different sort methods in order to do the comparison. (I think create class for each method may solve my problem. But I don't want to create too many class). So I decided to create one class called Sorts and bunch of sort functions under this class. I want to my sorted array reset to unsorted in order apply the same array to different sort method. Could anyone tell me how?
Generate data:
int size = Integer.parseInt(br.readLine());
int [] data = new int[size];
for (int i = 0; i< size; i++){
data[i] = (int)(Math.random()*(10*size));
System.out.print(data[i]+" ");
}
Create object:
Sorts sort = new Sorts(size, data);
Invokeļ¼š
switch(index){
case "1" :
System.out.print("\nYou select bubble sort\n");
sort.bubbleSort();
break;
case "2" :
System.out.print("You select quick sort\n");
sort.quickSort();
break;
My class:
class Sorts{
private int size;
private int data[];
Sorts(int size, int [] data){
this.size = size;
this.data = data;
}
protected void bubbleSort(){
int temp = 0;
for (int i = 0; i< (data.length-1); i++){
for (int j = 0; j<(data.length-1);j++){
if(data[j]>data[j+1]){
temp = data[j];
data[j] = data[j+1];
data[j+1]= temp;
}
}
}
printResult();
}
protected void quickSort(){
}
protected void resetData(){
}
}
Well, you could use Collections.shuffle, which takes a 'List' parameter. This would obviously mean converting your 'int[]' to 'List' (and back again).
Here's the java spec for 'Collections.shufffle'.
See the 'Collections.shuffle' tutorial on tutorialspoint.
There's also a sample array ('int[]') version on Vogella.
On another point, rather than implement it as you have, Ithink it's better to use the Strategy pattern to implement multiple sort mechanisms like this. For instance:
interface Sort {
void sort(int data[], int size);
}
class QuickSort implements Sort {
void sort(int data[], int size) {
...
}
}
class MergeSort implements Sort {
void sort(int data[], int size) {
...
}
}
etc...
As a further aside:
this is only sorting ints so consider how to sort any type (and perhaps generics).
some sorts (e.g. MergeSort) are stable and use new arrays to represent the sorted data. How can you return that to the caller? You can't set 'data' to your new array.
You can use the Method shuffle of the class Collection
Collection.shuffle(yourList);
This will shuffle your list automatically without implementing an own function.
After that you can convert the list back to an array. :)
I think for the usecase OP seems to have, the array just needs a reshuffling, this method reshuffles although there is no guarantee that it would reset it to the original array
private void reset(final int arr[]) {
Random rand = new Random();
for (int i = 0; i < arr.length; i++) {
int nextInt = rand.nextInt(arr.length);
int temp = arr[i];
arr[i] = arr[nextInt];
arr[nextInt] = temp;
}
}

filling values in array

what i want to do is fill the empty aray kyo[] with the add() method but it keeps getting an error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
0 at TestPlass.Add(TestPlass.java:30) at
TestPlass.main(TestPlass.java:18)
i'm just new to programming
public static int size = 30;
public static void main (String args[]) {
int kyo[] = {};
Add(kyo);
for(int x:kyo){
System.out.print(x + " ");
}
}
static void Add(int x[]){
for(int g=0; g<=size; g++){
x[g] = g;
}
}
If your kyo array has a fized size, you need to create it with this size.
public static int size = 30;
public static void main(String args[]) {
int kyo[] = new int[size];
add(kyo);
for (int x : kyo) {
System.out.print(x + " ");
}
}
static void add(int x[]) {
for (int g = 0; g < x.length; g++) {
x[g] = g;
}
}
You add function receives int x[] as input, so it should use x.length for the iterator and not your size variable.
I have also edited the name of your Add() method to be add() to respect Java code conventions.
An empty array can never have any content.
Once an array has been created, its size is fixed - you can change the content of the elements, but you can't change how many elements it has. See the Java arrays tutorial for more information.
If you need a dynamically-sized collection, I suggest you use a List<E> implementation, such as ArrayList<E>:
List<Integer> list = new ArrayList<>();
add(list);
for (int x : list) {
System.out.print(x + " ");
}
...
private static void add(List<Integer> list) {
// I assume you want "size" elements, not "size + 1"
for (int g = 0; g < size; g++) {
list.add(g);
}
}
This line:
int kyo[] = {};
creates an array of size zero. Arrays have a fixed size in Java; once an array has been created, its size is fixed. You have to create the array like this:
int[] kyo = new int[30];
This will create an array with 30 elements.
You need to give the size of the array when you create it, like:
int kyo[] = new int[size];
You can find some great info on arrays here:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Arrays do not resize themselves automatically, so the size you initialize it with will be its size forever.
Cheers,
Marcus
Your problem lies here: int kyo[] = {};
{} Creates an array of zero size. Since you are adding 31 elements to the array you need to initialize you array to appropriate size.
For example: int[] kyo = new int[31];

return an ArrayList of Integers that consist of n random numbers?

How do I create the method RandomArray and let it take in an integer n and return an ArrayList of Integers that consist of n random numbers between 0 and 255.(in other words: let the returned array be of size n)???
(I am using Java Eclipse)
I have created the RandomArray, however I do not know how to put it in an ArrayList, this is what I've got so far:
import java.util.Random;
public class Lab6 {
public static void main(String[] args) {
Random random = new Random();
int[] n = new int[1];
for( int i = 0 ; i < n.length ; i++ ) {
for ( int i1 = 0 ; i1 < n.length ; i1++ ) {
n[i1] = random.nextInt(255);
}
}
for( int a : n ) {
System.out.println( a );
}
}
}
ArrayLists work in much the same way as arrays, except they can grow (or shrink) as you want and do not support access/retrieval via the [] operator (i.e. you can't do n[i1] on an ArrayList). Instead, use its add() method to add elements to it and get() method to access elements.
You mean something like this:
public ArrayList<Integer> randomArrayList(int n)
{
ArrayList<Integer> list = new ArrayList<>();
Random random = new Random();
for (int i = 0; i < n; i++)
{
list.add(random.nextInt(255));
}
return list;
}
Try something like this
private ArrayList<Integer> randomArray(int size){
Random random = new Random();
ArrayList<Integer> newArrayList = new ArrayList<Integer>();
for(int i=0; i<size; i++){
int next = random.nextInt(256);
newArrayList.add(next);
}
return newArrayList;
}
Main method contains an example usage
import java.security.*;
import java.util.*;
public class Util {
public static void main(String[] args) {
int n = 15;
ArrayList<Integer> integers = RandomArray(n);
for (Integer integer : integers) {
System.out.println(integer);
}
}
private static ArrayList<Integer> RandomArray(int n) {
Random rand = new SecureRandom();
byte[] b = new byte[n];
rand.nextBytes(b);
Integer[] ints = new Integer[b.length];
for (int i = 0; i < b.length; i++) {
ints[i] = b[i] & 0xFF;
}
return new ArrayList<Integer>(Arrays.asList(ints));
}
}
This is more than you asked for, but it's tangentially related, and might help people coming across this question.
When you want an ArrayList of random integers, you often really just need some random numbers, and don't really need them stored anywhere. In such a case, you likely can get away with just an Iterator<Integer> that returns a stream of random integers, as many as you need. This is very easy to do with the Guava library (which nowadays should be part of every Java codebase).
You can easily define an Iterator<Integer> that gives you as many random ints (or any other data type you want) as you ask for:
public static final Iterator<Integer> RAND_INT_ITER =
new AbstractIterator<Integer>() {
#Override
protected Integer computeNext() {
return ThreadLocalRandom.current().nextInt();
}
};
Or if you want to use the Random.nextInt(int max) method:
public static Iterator<Integer> randIntIterator(final int max) {
return new AbstractIterator<Integer>() {
#Override
protected Integer computeNext() {
return ThreadLocalRandom.current().nextInt(max);
}
};
}
There's no issue with calling this method wherever you need it, since it stores no state you're not wasting time or space computing anything, and the garbage collector will clean it up for you when you're done. We use ThreadLocalRandom to ensure these are thread-safe and avoid constructing new Random objects all over the place (and the potential data-race conditions that introduces, though newer versions of Java are pretty smart about that). You could just as easily use an existing Random object if that made more sense.
Some examples:
// print random ints until we see one that's divisible by 100
while(true) {
int rnd = RAND_INT_ITER.next();
System.out.println(rnd);
if(rnd % 100 == 0) {
break;
}
}
// Get an iterator of exactly 10 random ints, [0,255)
Iterator<Integer> tenRandInts = Iterators.limit(randIntIterator(255), 10);
while(tenRandInts.hasNext()) {
System.out.println(tenRandInts.next());
}
// Note that the returned iterator above is still one-use, if you need to iterate
// Over the same numbers more than once, put them in a list first
// It's not a good idea to simply convert an Iterator into an Iterable, see:
// http://stackoverflow.com/a/14711323/113632
List<Integer> randIntLs = ImmutableList.copyOf(
Iterators.limit(randIntIterator(255), 10));
for(int rnd : randIntLs) {
System.out.println(rnd);
}
for(int rnd : randIntLs) {
System.out.println(rnd);
}
Using this pattern for random data generation will often make your code cleaner, leaner, and easier to read. Give it a try :)

Categories