HashCode For Calculating Different Objects
Jun 22, 2014
I'm trying to make a method that creates objects of a parameterized type randomly, but also to store the hashCode of different objects created and if at any time the percentage of different objects is less than 50% throw an exception.
This last part is where I've gotten stuck. I have created a population property where I store the different hashCodes and update it in the method adding the new hashCode from the new object. But I don't know how to do for to know if the percentage of different objects is less than 50%.
package fp.tipos.apps;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Random;
public class FactoriaApps {
[Code] .....
View Replies
ADVERTISEMENT
May 15, 2014
Its that very old question regarding hashcode and equals implementation which i am not getting .
import java.util.*;
public class MyElement {
public static void main(String a[]){
HashSet<Price> lhm = new HashSet<Price>();
lhm.add(new Price("Banana", 20));
lhm.add(new Price("Apple", 40));
[Code] .....
In the above program even if i comment out the Hashcode method , i believe it is still taking the memory address values from the native hashcode method of Object class. but the equals override implentation says that i have two insertions which are same . So as per my logic it should not allow the duplicate element to enter.but its not so ...the duplicate element is well inserted without hashcode .
View Replies
View Related
Mar 4, 2014
The assignment goes like this...Write a Payroll class that uses the following arrays as fields:
employeeID - An array of seven integers to hold employee identification numbers. The array should be initialized with the following numbers:
5658845452012578951228777541
845127713028507580489
hours - An array of seven integers to hold the number of hours worked by each employee.payRate - An array of seven doubles to hold each employee's hourly pay rate.wages - An array of seven doubles to hold each employee's gross wages.The class should relate the data in each array through the subscripts.
For example, the number in element 0 of the hours array should be the number of hours worked by the employee whose identification number is stored in element 0 of the employeeID array. That same employee's pay rate should be stored in element 0 of the payRate array. In addition to the appropriate accessor and mutator methods, the class should have a method that accepts an employee's identification number as an argument and returns the gross pay for that employee.Demonstrate the class in a complete program that displays each employee number and asks the user to enter that employee's hours and pay rate. It should then display each employee's identification number and gross wages.Input Validation: Do not accept negative values for hours or numbers less than 6.0 for a pay rate.
My problem with this program is that everytime I try to print the employee ID's or the wages, I get hashcode or something like it (#[I1a77cdc or something like that). I tried using the toString method, but it lists all of the values, when I'm trying to display one at a time. Here is the code for the class:
// moduleArray class
public class moduleArray {
final int NUM_EMPLOYEES = 7;
int[] employeeID = {5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 7580489};
int[] hours = new int[NUM_EMPLOYEES];
[code]...
This is the demo program to list the ID's. I've been messing with it for some time, and right now I just want it to display values.
import java.util.Scanner;
public class moduleArrayDemo {
public static void main(String[] args) {
final int NUM_EMPLOYEES = 7;
int[] ID = new int[NUM_EMPLOYEES];
[code]...
View Replies
View Related
Mar 11, 2014
I am studying Serialization from the SCJP 6 Kathy Sierra book. I came across this code snippet.
public class Cat implements Serializable {
public static void main(String[] args) {
Cat c = new Cat();
try {
FileOutputStream fs = new FileOutputStream("testSer.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
[code]....
The output is as follows.
files.Cat@4d43691d
files.Cat@7f39ebdb
1) Why are the two hashcodes different?
2) Serialization is supposed to make and identical copy of any object and all its instance variables. So, if the hashcodes are different, are these objects located in different locations in heap?
View Replies
View Related
Jul 17, 2014
Winston Gutkowski in one of the threads that one of the advatanges of String being immutable is that its hashcode could be cached. How does this work? I read somewhere that each String's hashcode is stored in a private int variable, but I don't understand how it is reused.
View Replies
View Related
Jul 7, 2014
I read this tutorial about overriding equal and hashcode method. [URL] ....
I understand how to override equal method, by overriding it, We can custom our compare. I also understand How to override hashcode, To make custom hash.
But still I can not understand why we do it? why if equal method override, we must override hashcode method too?If we don't what is the problem?
To honor the above contract we should always override hashCode() method whenever we override equals() method. If not, what will happen? If we use hashtables in our application, it will not behave as expected. As the hashCode is used in determining the equality of values stored, it will not return the right corresponding value for a key.
Is it the right reason in order to override:
Because when we customize equal method so it focus on special variables,We must change the hash code too in order to match with it, so hashcode also focus on those special variable.
View Replies
View Related
Nov 3, 2014
I want to extend hashCode method in my class. As we know that hashCode is generating with 32 bit. Now I wanna generate 64-bit hashCode for user given Input.. Input may be string or Integer.
Please let me know.. take me out from this problem..
MY code follows like this...
package hash_table;
public class Hash_table
{
private int num;
private String data;
public boolean equals(Object obj)
{
if(this == obj)
[Code]...
View Replies
View Related
Jul 17, 2014
Here is my code the whole program is working correctly but the Boolean equals and the has code and it is a requirement for the assignment. Why it is not working.
I know there are issues with the code I am new with java and was struggling so I have to clean my code up before I submit the assignment but for right now I have the out put the way I want it except the Boolean and hash code methods always output that the rectangles aren't equal even when I know they are and it outputs the not equal statement twice??
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.Scanner;
[Code] ....
View Replies
View Related
Jul 11, 2014
The keys in a HashMap and the values in a Set must all be unique, but this can be circumvented when using custom objects in a HashMap and Set, because the compiler has no way to determine if the objects are equal or not, as shown in the example below:
Java Code:
import java.util.LinkedHashMap;
import java.util.Map;
public class HashCodeEquals {
public void run(){
Person p1 = new Person(1, "John");
Person p2 = new Person(2, "Matt");
Person p3 = new Person(1, "John");
[code]....
Obviously the equals method is needed because that compares the two objects. But why is the hashCode method needed?
View Replies
View Related
Jan 16, 2015
I am trying to implement the following example to override the equality and hashCode method if the class has reference type member. I do get the expected result "true" for equal and "false" for non-equal objects. But the print statement in the Circle's equal method is not executed when the objects values are not equal. I don't know what i am missing, though i get the equality result "false" as expected for non equal objects.
class Point{
private int x, y;
Point (int x, int y) {
this.x =x;
this.y = y;
[code]....
View Replies
View Related
Jul 27, 2014
I am currently working on a project where I need to return data from a database over RMI to a client who requests it. Some of the fields in the Data Object can not be seen by the client so I need to create another object to send over the network instead. The method I use is this...
public static SerializableObject createSerializableObjectFromDataObject(DataObject dataObject){
SerializableObject serializableObject = new SerializableObject();
serializableObject.setField(dataObject.getField());
serializableObject.setAnotherField(dataObject.getAnotherField());
return serializableObject;
}
Is there a better way of doing this? I am creating many subclasses DataObject which all require this static method to be implemented and I can't push it into the superclass because each one needs custom behaviour.
View Replies
View Related
Oct 23, 2014
USING A WHILE OR A DO-WHILE LOOP write a program to compute PI using the following equation:
PI = 3 + 4/(2*3*4) - 4/(4*5*6) + 4/(6*7*8) - 4/(8*9*10) + ...
Allow the user to specify the number of terms (5 terms are shown) to use in the computation. Each time around the loop only one extra term should be added to the estimate for PI.
Alter your solution from part one so that the user is allowed to specify the precision required between 1 and 8 digits (i.e. the number of digits which are correct; e.g. to 5 digits PI is 3.14159), rather than the number of terms. The condition on the loop should be altered so that it continues until the required precision is obtained. Note that you need only submit this second version of the program (assuming you have it working).
View Replies
View Related
Sep 14, 2014
I'm trying to calculate sin(x) without using Math.sin(x). The formula for sin(x) is: x - x^3/3! + x^5/5! ... I can't seem to get the coding for the alternating +/- right. Here's my program:
import java.util.Scanner;
import java.lang.Math;
class Sin
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
int n, c, fact = 1, count = 1;
double x, sum = 0, sum_sin = 0, result;
[Code] ....
View Replies
View Related
Mar 2, 2014
I'm working on some exercises and I'm having some problems with a method. I want to create a method to calculate the Factorial of an int number. I already wrote code that asks the user to input an int number and it calculates the Factorial, and it works fine
i.e.: if I input 5 it outputs
5! = 120
as it should. Here's the code:
import java.util.Scanner;
public class Factorial1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number;
int total = 1;
[Code] ....
Now I want to make a method to re-use this code in other programs and I wrote this program:
public class TestClass {
public static void main(String[] args) {
System.out.print(factorial(5));
}
public static int factorial(int x) {
int total = 0;
[Code] ....
But when I run this program it outputs 0 instead of 120. What is wrong with this code as it compiles just fine but doesn't work as intended.
View Replies
View Related
Oct 7, 2014
I am trying to calculate factorials using BlueJ. All of my factorials calculate correctly, I am just having an issue with something the instructor asked of us. She asked us to force the loop to stop when the user inputs "Calculate the factorial of 0", and not give any print.
So far I have my for loop with the correct conditions, I am just really confused as to how to make an if statement to stop the code when the input is 0.
View Replies
View Related
Apr 21, 2014
I'm struggling with this assignment I was given:
Given list of positive integer values, write a program to calculate average of the values. List terminates with -1.
View Replies
View Related
May 26, 2014
I am working on the first example in this java game programming book. I am having trouble understanding this basic concept. How does the delta variable work throughout this class? I know the syntax I just don't understand the concept fully.
Explain these components of the program:
1) delta += current-lastTime works
2) lastTime = current;
3) if(delta > 1000)
{
delta-1000
....
}
package javagames.util;
public class FrameRate {
private String frameRate;
private long lastTime;
private long delta;
private int frameCount;
[Code] .....
View Replies
View Related
Jun 5, 2014
what I'm missing to calculate the Total Payout that Payroll has given out to two employees. the professor states that we have to use "getTotalPayout" . It would have been easy to do "(employee1.getFinal() + employee2.getFinal())" but he use getTotalPayout.
public class Payroll
{
private String employeeId;
private int hourlyrate, hoursworked;
private int increaseHours = 10;
private double TotalPayout;
[code]....
View Replies
View Related
Sep 9, 2014
I am supposed to be doing a class assignment that calculates the area of a triangle and outputs with JOptionPane. I was able to fix some errors, but it's uncovering more errors.Here is my code:
import javax.swing.JOptionPane;
import java.util.*;
import java.text.DecimalFormat;
import java.util.StringTokenizer;
public class Area {
public static void main (String [] args) {
double a, b, c; //Input sides of triangle
double x; //Perimeter of triangle
double area; //Area of triangle
StringTokenizer st;
[code]....
View Replies
View Related
Feb 24, 2014
write a program that reads in the year, month, and day of a couple's wedding date and compute thier next wedding anniversary after March 2, 2011.
TThis has to be input in a message dialog box also.
View Replies
View Related
Mar 25, 2015
I'm currently in the process of creating a shopping cart simulation. The main GUI consists of two lists, one is a list of the inventory. (products stored within a .dat file which is automatically loaded upon launch) The other is blank and is to model my shopping basket. The idea is to be able to scan items from my inventory into the checkout basket. As this is happening i want a text field i created to dynamically update with the cost of all the items in the basket.
Below is the method for my scan button, which is supposed to perform the above :
public void actionPerformed(ActionEvent evt) {
//Get the newly added list values.
JList list = productList.getSelectedValuesList();
double totalAddedValue = 0.0;
double oldCartValue = 0.0;
[code]...
View Replies
View Related
Feb 21, 2014
I am trying to do the following java assignment and every thing seems to work fine except when I put a number<4 or >10 it prints both "Invalid grade!"
"You didn't enter any data!" what I wanted is to print only "Invalid grade!" I tried to fix it but I couldn't.
Create a program that asks for results of exams and calculates the mean average of the grades. Grades are floating point numbers between 4 and 10. Program asks for grades until a negative number is typed. If user gives a grade other than a number between 4 and 10, the text "Invalid grade!" will be printed on screen and program asks for another grade. Finally the program prints the number of inputted grades and their mean average on screen as shown in the example print. If no grades were inputted, the notice "You did not input any grades." is the only thing printed on screen.
A double type variable is to be used to store the value of the average.
Program is written to a class called Average.
Example output
Program calculates the average of inputted grades.
Finish with a negative integer.
Input a grade (4-10): 5
Input a grade (4-10): 6,5
Input a grade (4-10): 7,5
Input a grade (4-10): 7
Input a grade (4-10): 0
Invalid grade!
Input a grade (4-10): -4
4 grades inputted.
Average of the grades: 6.5
Java Code:
import java.util.Scanner;
public class apples {
public static void main(String[] args)
int inputNumber=0;
int sum;
int count;
double average;
[Code] .....
View Replies
View Related
Apr 21, 2014
Here is the code that I wrote out:
//program that calculates the circumference and area of a circle
import java.util.Scanner;
public class circle{
public static void main(String[] args){
Scanner input= new Scanner( System.in);
double r; //declares radius
[Code] .....
And here is what is displayed in the command prompt when I compile my code:
circle.java:17: error: cannot find symbol
r.input.nextdouble();//entered the radius
symbol: method nextdouble()
location: variable input of type Scanner
1 error
What am I doing wrong?
View Replies
View Related
Mar 30, 2015
//calculates rainfall quarterly per year
import java.util.Scanner;
public class SophiaKeyProgram2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int numQuarter; //number of quarters in a year
double rainfall=0; //the amount of rain
[Code] ....
View Replies
View Related
Oct 24, 2014
I have to print points on a circle in increments of -0.1, but when I use a number larger than 1.3, the list stops at 0.1 larger than negRadius, and I don't know why. (Assume the center is (0,0))
public class PointsOnACircleV1
{
public static void main(String[] args)
{
double radius = 1;
[code]...
View Replies
View Related
Feb 27, 2015
i want it to calculate my earnings say for 4 months and then output the result. it runs the loop asking for the 4 months worth of earnings but then it shows just the amount entered for the month and not total.
package Earnings;
import java.util.Scanner;
import java.lang.Math;
public class Earnings {
public static void main(String[] args) {
[code]....
i tried changing from double month to String month but it doesn't work.
View Replies
View Related