Trying to print out the contents of an ArrayList - java

I'm trying to print out the contents of the ArrayList "list", but I keep getting what I think is the locations of the elements and not the contents.
import java.util.*;
public class Assignment23 {
public static void main (String[] args){
ArrayList<Point> list = new ArrayList<Point>();
for(int i = 0; i < 99; i++){
list.add(new Point());
}
Collections.sort(list);
System.out.println(""+list);
}
}
class Point implements Comparable<Point>{
int x = (int)(Math.random()*-10);
int y = (int)(Math.random()*-10);

To print out the contents of the ArrayList, use a for loop:
for (Point p : list)
System.out.println("point x: " + p.x ", point y: " + p.y);

You will find you get much better results for this and in many situations if you implement toString for Point and most classes that you write. Consider this:
#Override public String toString()
{
return String.format("(%d,%d)", x, y);
}

Over write toString method in point
class Point implements Comparable<Point>{
int x = (int)(Math.random()*-10);
int y = (int)(Math.random()*-10);
#Override
public String toString()
{
return "["+x+","+y+"]";
}
}
Usage is same :
Collections.sort(list);
System.out.println("Points["+list+"]);
You will get output like
Points[[20,10],[15,10]...]

Override toString() method on Point class.
class Point implements Comparable<Point>{
#Override
public String toString() {
return "x =" + x + ", y="+y;
}
}

Change it to:
System.out.println(""+list.get(i).x); //Or whatever element in `Point` you want to print
The reason you were getting an unexpected result is that your list consists of Point objects. So calling list.get(i) returns an entire Point, whereas you want to specify that field in the Point to print out.

Related

HashMap Storing only one entry

I'm taking a binary String like this:
010010010000110100001010
as a String, converting it to Integer Array like this:
int[] DD = new DD[binString.length()];
char temp = binString.charAt(i);
int binData = Character.getNumericValue(temp);
DD[i] = binData;
and I'm tying to save these Integer values in to HashMap(I have to store into a HashMap as per instructions given to me) like this:
Map<String, Integer> toMemory = new HashMap<String, Integer>();
for(int i=0;i<binString.length();i++) {
char temp = binString.charAt(i);
int binData = Character.getNumericValue(temp);
DD[i] = binData;
if((DD[i] & (DD[i]-1) ) == 0) {
toMemory.put(new String("ON"), new Integer(DD[i]));
} else {
toMemory.put(new String("ON"), new Integer(DD[i]));
}
}
for(String s: toMemory.keySet()) {
if(s.startsWith("ON")) {
System.out.println(toMemory.get(s));
}
}
The issue I'm facing here is that, only one entry is being stored in the HashMap, say {"ON",0}. And no other values are being stored. My expected output is this:
{"ON" , 1 , "OFF" , 0, "ON" , 1 .........}
Is there any better way to store the values to get my expected output? Any help will be much appreciated.
P.S: Please ignore the recurring code, and I'm relatively new to programming.
Your usage of a Map is flawed. Maps take a unique key and return a value.
You are trying to use duplicate keys. Instead, look at using a List with a wrapper class:
class ClassName {
public String status;
public int value;
public ClassName(String status, int value){
this.status = status;
this.value = value;
}
}
List<ClassName> list = new ArrayList();
To add to the list, create a new instance of your class and call List#add:
list.add(new ClassName("ON", 1));
as Infuzed Guy said, you are using the Map the wrong way. It's a unique "key to value mapping".
As long as you are using several times the same key and want to store all the dada, you need to use a List.
Here is what I could come up with the little you gave us: test it here
import java.util.LinkedList;
import java.util.List;
class Main {
public static void main(String[] args) {
class Tuple<X, Y> { //The wrapper object
public final X x;
public final Y y;
public Tuple(X x, Y y) { //Object constructor
this.x = x;
this.y = y;
}
public String toString() //Here for printing purpose
{
return "\"" + this.x + "\", " + this.y;
}
}
//Note here te use of List
List<Tuple> toMemory = new LinkedList<>();
String binString = "10100100101100101011";
int[] DD = new int[binString.length()];
for(int i=0; i < binString.length(); ++i)
{
//Here I use the char value
//to get the by subtraction
DD[i] = binString.charAt(i) - '0';
if(DD[i] == 1) //Simple check with the int value
{
toMemory.add(new Tuple<>("ON", DD[i]));
}
else
{
toMemory.add(new Tuple<>("OFF", DD[i]));
}
}
//Print the List
System.out.print("{ ");
for(Tuple s: toMemory) {
System.out.print(s +", ");
}
System.out.println("}");
}
}

Unexpected endless loop appears

I've got an ArrayList filled with 500 Point-Objects. There might be duplicates in it so I want to find them and if needed delete them except for one. The plan is: Check for each Point in the arrayList, if there is an equal Point, if so, add it to a List, after the test for each Point, delete all Points from the original List that are also in the toRemove-List.
But here comes the Problem: If i run this, its going for an endless loop. Do I have a serious thinking error? I think it might be a really simple misstake but I cant think about it
Also, if you have any proposal on how to do this better, let me know.
This is my method:
private void checkForDuplicates() {
ArrayList <Point> toRemove=new ArrayList<Point>();
int i=0;
while(i<points.size()) {
Point local=points.get(i);
for (Point p: points) {
if (local!=p && local.equals(p)) {
toRemove.add(p);
}
}
for (Point p: toRemove) {
points.remove(p);
}
i++;
}
}
Update:
Something is really broken. It looks like the method might work right now, but my programm isnt. The code isnt running anymore if I call this method somewhere. I cant even print out something on the console as the first line in my main method while i call checkForDuplicates() somewhere else?!
Point:
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
#Override
public boolean equals(Object p) {
if (this == p) {
return true;
}
if (!(p instanceof Point)) {
return false;
}
Point point = (Point) p;
return this.getX() == point.getX() && this.getY() == point.getY();
}
}
I recommend using streams for this task:
List result =
points
.stream()
.distinct()
.collect(Collectors.toCollection(ArrayList::new));
To make distinct() work as expected, you will probably have to define an equals()method for your Point class.
User Frank Puffer has answered the question in Java 8. It seems as if you're in older version of Java, so the following might help you. It just creates a Set object and copies the ArrayList to it. Because the Set will remove the duplicates automatically you don't need to make the code much more complexer than it should be, and is less error prone.
private void removeDuplicates() {
Set<Point> distinctPoints = new HashSet<>();
for (Point p : points) {
distinctPoints.add(p);
}
points = new ArrayList<String>(distinctPoints);
}
And include the following method impl to the Point class so that Point objects can be searched in the Set:
#Override
public int hashCode() {
int hashValue = 11;
hashValue = 31 * hashValue + x;
hashValue = 31 * hashValue + y;
return hashValue;
}
#Override
public String toString() {
return "Point[" + X + ", " + Y + "]";
}
The toString() method is a nice to have feature.

Printing Out a hashset to screen

I am attempting to print out a hashset taking in records from a database which are currently stored in two seperate ArrayLists. When I attempt to print out the HashSet the following error shows.
This is your HashSet[nyu.Sorting#378bf509, nyu.Sorting#7b23ec81, nyu.Sorting#15aeb7ab, nyu.Sorting#27d6c5e0, nyu.Sorting#7ef20235, nyu.Sorting#4f3f5b24, nyu.Sorting#6acbcfc0, nyu.Sorting#2d98a335, nyu.Sorting#5fd0d5ae, nyu.Sorting#16b98e56]
And this is my code:
public static HashSet<Sorting> t() {
Sorting s = new Sorting();
int TimeNeededOne = 75;
int TimeNeededTwo = 75;
int assignedTimeOne = 0;
int assignedTimeTwo = 0;
HashSet<Sorting> c = new HashSet<Sorting>();
for(int i=0; i<=i1.size()-1; i++)
{
if((assignedTimeOne < TimeNeededOne) && !(assignedTimeOne+ i1.get(i).getLengthMins() > offensiveTimeInMins) )
{
c.add(i1.get(i));
assignedTimeOne += i1.get(i).getLengthMins();
}
}
for(int i=0; i<=i2.size()-1; i++)
{
if((assignedTimeTwo < TimeNeededTwo) && !(assignedTimeTwo + i2.get(i).getLengthMins() > TimeNeededTwo) )
{
c.add(i2.get(i));
assignedTimeTwo += i2.get(i).getLengthMins();
}
}
System.out.println("Training programme :" + c.size());
System.out.println("This is your training programme" + c.toString());
return c;
}
The c.size is there to confirm that ten entries are made which is correct however the formatting of the records from the hashset obviously contains a problem. Any help with this issue would be greatly appreciated.
Thanks.
One way of doing this would be to override the toString() method of your Sorting class to print its contents:
public class Sorting {
...
#Override
public String toString() {
// Return a String that represents this object
return "...";
}
}
You need override toString() method in the Sorting class, for example:
class Sorting {
...
#Override
public String toString() {
// a string representation of Sorting object
}
}
java.util.Iterator runs through the whole collection and for each element invokes a toString() method. The data recorded in the java.lang.StringBuilder, which returns of its string representation at the end.

Java considering List argument as reference

I was doing some RnD I came across this this difference
my java code is as below
public class Main {
public static void main(String[] args) {
Integer x = 10;
increment(x);
System.out.println("print x" + x);
List<String> strList = new ArrayList<String>();
strList.add("one");
strList.add("two");
strList.add("three");
strList.add("four");
strList.add("five");
strList.add("six");
System.out.println("Before removing");
for (String string : strList) {
System.out.println("item " + string);
}
removeSomeItem(strList);
System.out.println("After removing");
for (String string : strList) {
System.out.println("item " + string);
}
}
private static void removeSomeItem(List<String> strList) {
strList.remove(0);
strList.remove(4);
}
private static void increment(Integer x) {
x++;
}
}
I got out for the above code as below
print x10
Before removing
item one
item two
item three
item four
item five
item six
After removing
item two
item three
item four
item five
my question is when I had sent Integer to function it behaved like value same way when I had sent List<String> its behaving like reference why is this difference ?
can any one explain
The main difference is that the Integer class is immutable, hence why you do not see the change in your main method.
x++; // this will simply return a new Integer
To see the difference, try this from your main method:
x = increment(x);
and in the increment method, change it to this:
return x++;
However, with your list example, you are simply passing a copy of the reference to the list. As long as that reference is not set to a new object (which it isn't), it is able to update the original list you passed.
This is exactly what happened
private static Integer b;
public static void main(String[] args) {
Integer x0 = 10;
b = x0;
increment(x0);
}
private static void increment(Integer x1) {
//x1 == b is true
x1++; //implies x1 = x1 + 1;
//x1 == b is now false
//at the end of the day, you've done nothing to x0 or b
}
EDIT: This code will fail because apparently, the JVM is caching Integer values between -128 and 127, see here, set x0 = 150 and test.
public class Main {
static Integer b;
public static void main(String[] args) {
Integer x = 150;
b = x;
increment(x);
}
private static void increment(Integer x) {
System.out.println(x == b); //true
x++;
System.out.println(x == b); //false
b++;
System.out.println(x == b); //false
}
}
Well in case of,
removeSomeItem(strList);
you are passing the address of original ArrayList to the method so when it remove some value using that reference the original ArrayList change too (actually they are single object with two access point , I mean the reference ).
But in case of Integer you also pass the reference and the increment(Integer x) method receive the original reference. But as Integer immutable when I do something like,
x++;
In the background its work like
x=new Integer(x+1);
That’s why the original Integer remain unchanged when the ArrayList change.

Object Creation in java and finalize

class FDemo {
int x;
FDemo(int i) {
x = i;
}
protected void finalize() {
System.out.println("Finalizing " + x);
}
void generator(int i) {
FDemo o = new FDemo(i);
System.out.println("Creat obj No: " + x); // this line
}
}
class Finalize {
public static void main(String args[]) {
int count;
FDemo ob = new FDemo(0);
for(count=1; count < 100000; count++)
ob.generator(count);
}
}
}
In the line i have commented, the value of x always shows 0(value of x in object ob), why isnt showing the value of object o?? i know if i use o.x i ll be getting the value of x in object o. But still in this code why does it show the value of abject ob rather than object o??
If you want to reference the x in the FDemo you've just created, you should add a getX() function and call that instead of x, like David Wallace said. (I prefer using getters instead of .variable).
Add this to your class:
public int getX(){
return x;
}
And change your problematic line to this:
System.out.println("Creat obj No: " + o.getX());
That should fix it. As a side note, it's considered good practice to explicitly declare whether your variables and methods are private, public or protected.

Categories

Resources