Best Way To Keep Track Of Number Of Objects Created
Mar 13, 2014
Which is the best way to keep track of the number of the objects I've created?Is is a good practice to have a static variable, which will be incremented everytime I call a contructor?
Class circle{
private double x,y,radius;
private static count;
Circle(double x1, double y1, double radius1){
x=x1;y=y1;radius=radius1;
count++;
}
View Replies
ADVERTISEMENT
Jan 19, 2014
String s= new String ("Hello");
String a = new String ("Hello");
As per my understanding the first line creates 2 objects : 1 for the heap memory and 1 for String pool
2nd line : new object created and no new object created in the String pool as the keyword already exists in the pool.
So the total number of objects created after the execution of 2 lines are : 3
View Replies
View Related
Aug 15, 2014
how many objects got created at each line (in String pool or in Objects memory):
public class Test {
public static void main(String[] args) {
String s1 = "test";
String s2 = new("test");
String s3 = s1 + s2;
StringBuider sb = new StringBuilder().append(s2);
}
}
View Replies
View Related
May 22, 2014
I am little confused about String creation in java.
Doubt 1: How String objects assigned to Pool area:
1. String s="in pool";
2. String s1= new String("not in pool");
How many objects created in statement 1 and 2. According to recent discussion with my colleague, one object created in String pool in case 1. And in case 2, two objects are created, one as literal goes to String pool and other with new() opr goes to Heap.
If above is correct, Ain't we wasting double memory for same object ? Really need clear understanding on this
Doubt 2: How does intern() work: Please see if my below explanation is correct
1. If String literal is already present in String pool , and i create a same string with new operator, reference to object is changed to pool area.
2. If String object is created using new operator and intern is called on it. If same string object is not present in the String Pool, Its moved to String pool and reference to this in Pool is returned.
View Replies
View Related
Mar 8, 2014
coding the action listener for my button (btBody) which create button displaying 1 to 9 in a nested for loop; the button should allow the user to click on them and to display the number clicked on in a JTextField;my code;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class EX_7_2 extends JFrame
{
public EX_7_2()
{
setLayout(new BorderLayout(5, 10));
[code]....
View Replies
View Related
Jan 30, 2014
I am trying to restrict the number of views in JSF 2.0.2 using
<context-param>
<param-name>org.apache.myfaces.NUMBER_OF_VIEWS_IN_SESSION</param-name>
<param-value>5</param-value>
</context-param>
In my case my managed bean is View Scoped and it supports a UI page which has multiple forms and each form is submitted as AJAX POST request.
As per the statndard, setting restriction to 5 should create 5 views and after that based on LRU algorithm the oldest views should get deleted if 6th views is created.
Therefore any action on the oldest view will throw the ViewExpiredException and i simply redirect the user to view expired page.
1) When i set the restriction to 5 views, i open 4 tabs with 3 forms each.
2) I submit the 3 forms on first tab everything works fine.
3) As soon as I go to 2nd tab and submit the first form thr, i get view expired exception
4) It seems I am exceeding the number of views I mentioned in web.xml
I want to know :
1) Does every AJAX POST submit itself creates a view ?
2) How I can count the number of views created in a session ?
3)Can i force expiry of a view in JSF 2.0.2 while the session is still alive ?
4) Normally JSF 2.0.2 session cachces the views. Lets assume session is alive the entire day but a view was created in morning at 9:00 AM and is not used again the entire day. Assuming that session doesn't reaches the max number of views it can save in entire day, will the view created in morning expire on its own after certain interval of time ? If not , can we still force its expiry while keeping the session alive ?
View Replies
View Related
Mar 17, 2014
I am trying to find a concise way to write the sort methods for my class. I am supposed to make a program that can sort objects by a number of fields: year, rank, artist and title.
I used an idea from this thread : java - Sorting a collection of objects - Stack Overflow
And I am trying to use the custom comparator for my sort methods. However for some reason, the sortingBy variable fails to recognize any of the enum types.
Whenever I try to set the sortingBy variable equal to one of them, for example:
Java Code:
private Order sortingBy = Year; mh_sh_highlight_all('java');
I get a "Year cannot be resolved to a variable" error.
What I want to be able to do is make it so every time a specific method is called, say, for example sortTitle(), sortingBy will change to Title, then the SongComparator will sort using the case Title.
Is it possible to do this? I can't figure out how to modify SongComparator's object variables that way.
Java Code:
import java.util.Comparator;
public class SongComparator implements Comparator<Song> {
public enum Order {Year, Rank, Artist, Title}
public Order sortingBy;
[Code] .....
View Replies
View Related
Apr 20, 2015
I have application written in rest with Jersey-Jackson for JSON processing. All the resources produce and consume JSON. Now, the problem is, it is a server intensive application and large number of request will be hitting the server with large JSON request object. Now, because of this reason, when the JSON object gets converted in to Java object with String fields in it mapping to JSON request values large number of string objects are getting created which is resulting in frequent GC.
View Replies
View Related
Jul 8, 2014
I have a problem with my application. It supposed to store 4 different Room objects but when I entered one only it stores tat object variables into all my Array elements. I just need it to store any number of objects as long as it is less than 4.
Java Code:
import java.util.Arrays;
import java.util.Scanner;
import javax.swing.JOptionPane;
class TestRoom {
public static void main(String [] args)
{
String[] roomsInHouse = new String[4];
[Code] .....
View Replies
View Related
Sep 22, 2014
Part of my program requires writing a function that determines the number of subsets of k items that can be chosen from a set of n distinct objects ("n choose k" or n!/((n-k)! n!)). The only errors I am getting are from the first line of the function:
// n choose k: distinct subsets of k items chosen from n items
public static int choose (int n, int k) {
if (k <= 0)
return 1;
else
return choose(n--, k--) * (n/k);
}
View Replies
View Related
Nov 25, 2014
So I have a player an enemy and enemy bounds the enemy can go. I need to have the enemy track my position and when I go into the position (I am using a collision method for this) the enemy comes over at a speed of 1. My problem is the enemy jumps to me and then follows at speed of 2 (2 is the player speed). The code is wrong this is why it is jumping and I have my other problems. so my question is what is a good solution for this? I am trying to make a method to track playerposition() so what I am thinking I could do is find x, y of player then store those into an array and return the array to Enemy so he tracks.
player.java
public class Player{
int x = 100; // Location of player
int y = 200; // location of player
int xa = 0; // Representation of where the player goes
int ya = 0; // Representation of where the player goes
private int speed = 2;
[Code] .....
Please note this is not the entire code I have cut some things out that did not need to be there. Also, the code is just to get an idea of what I was thinking of doing. The ideas that are came up with are not meant to be a reflection of what I already have but, what I could add or replace.
View Replies
View Related
May 20, 2014
I'm trying to make a canteen class that holds water. It holds two quarts of water and two quarts is 100%.
public double maxVolume;
public int percentFull;
Right now the Canteen is empty.
public void Canteen()
{
percentFull=0;
maxVolume=0;
}
And right now I'm trying to make a constructor that specifies the amount of liquid the canteen can hold and specifies the percent full.
public Canteen(double maxVolume, int percentFull)
{
}
Should I make this second Canteen an integer, a double, or something else? Also, how do I make sure the Canteen never reaches higher than 100%. I'm also curious how I can keep maxVolume and percentFull connected so the % of water is consistent with the number of quarts(2) the Canteen can hold.
View Replies
View Related
Aug 31, 2014
I have two JFrames: frame1 and frame2. frame2 currently has focus, and I want to determine which component of frame1 would have focus if I were to switch focus to frame1, hopefully without actually temporarily changing focus.
Is it the KeyboardFocusManager who keeps track of which element in each frame has focus? Or does each container itself keep track? How does Java figure out which element in a frame gets focus when I switch to that window?
View Replies
View Related
Mar 8, 2014
The code I have below asks the user how many times you want to roll the dice. It rolls dice 1 and dice 2 randomly and gives the total. Now, I'm trying to keep track of the result of each roll using an array that is indexed by the sum of the roll of the two dice. Then I want to output my result in a table that shows each value (from 2 - 12)) and the number of times that value was rolled. I would like to do this preferably with the JTextArea class, but it doesn't have to be. I keep getting errors.The code below works for the dice rolling in the 1st paragraph. I took out all the bad code I was trying to use for the 2nd paragraph.
package Part2pack;
import java.util.Random;
import javax.swing.JOptionPane;
class Dice{
public static void main (String args[])
{
String input = " ";
int count = 0,dice1,dice2;
[code]....
View Replies
View Related
Nov 10, 2014
Basically we have to create a calculator that it will have to keep track of the current value, and do the functions that the calculator uses.
But I have it working for the most part, but the current value does not keep...
The double " currentValue " Must stay private.
import java.util.*;
public class MemoryCaluclator {
private double currentValue;
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
int answer = 0;
[Code] ......
View Replies
View Related
Jan 13, 2015
I need to make a program that keeps track of peoples names, allows you to add a note to each name and preferably would reorganize whatever you put in by date or by spelling. (I suppose the phonebook application in cell phones is a good match, a supermarket's list of foods and prices would work as well).
View Replies
View Related
Jan 23, 2015
I am currently truing to make this class instantiate 100,000 dice rolls of 2 dice. And I also need to keep track of how many times each possible total occurs and I am having trouble outputting the result. Right now when I run my code it is just showing the results of each of the 100,000 roles.
public class ltefera_DiceRollTest {
public static void main(String[] args) {
ltefera_DiceRoll diceRoll = new ltefera_DiceRoll(10);
System.out.println("Total # of pips" + "
");
diceRoll.printArray();
System.out.println(diceRoll.countDice(2));
System.out.println(diceRoll.isArrayDataValid());
System.out.println(diceRoll.getTotal());
System.out.println(diceRoll.allDifferent());
[code]....
"how many time each possible total occurs"
View Replies
View Related
Apr 18, 2014
Here are my conditions: You are developing a program to keep track of team standings in a league. When a game is played, the winning team (the team with the higher score) gets 2 points and the losing team gets no points. If there is a tie, both teams get 1 point. The order of the standings must be adjusted whenever the results of a game between two teams are reported. The following class records the results of one game.
public class GameResult
{
public String homeTeam() // name of home team
{ /* code not shown */ }
public String awayTeam() // name of away team
[Code] ....
The class TeamStandings stores information on the team standings. A partial declaration is shown below.
public class TeamStandings
{
TeamInfo[] standings; // maintained in decreasing order by points,
// teams with equal points can be in any order
public void recordGameResult(GameResult result)
[Code] ....
And here is the actual question:
Write the method adjust. The method adjust should increment the team points for the team found at the index position in standings by the amount given by the parameter points. In addition, the position of the team found at index in standings should be changed to maintain standings in decreasing order by points; teams for which points are equal can appear in any order.
And here is what I have so far:
private void adjust(int index, int points)
{
int Score[] = new int[standings.length]
for ( int i=0; i <= standings.length; i++)
{
Score[i] = index, points;
}
}
View Replies
View Related
May 4, 2014
I'm working on a lab for my class. I need to create a Priority Queue in Java using an array list. The kicker is that each node has to have a "handle" which is just an object which contains the index of of the node that it's associated with. I know that sounds weird but we have to implement it this way. Anyway, my priority queue seem to work fine except the handle values apparently aren't updating correctly because I fail the handle test. Also, I run into problems with handles only after extractMin() is called, so I figured the problem would be somewhere in that method but I've been through it a million times and it looks good to me.
Here is my Priority Queue Class:
package lab3;
import java.util.ArrayList;
/**
* A priority queue class supporting operations needed for
* Dijkstra's algorithm.
*/
class PriorityQueue<T> {
final static int INF = 1000000000;
ArrayList<PQNode<T>> queue;
[Code] ....
I can post the tests too but I don't know if that would do much good. Just know that the queue works as is should, but the handles don't point to the right nodes after extractMin() is utilized.
View Replies
View Related
Apr 27, 2014
I've built up an unreasonably large and unreasonably complicated JPanel. Unfortunately, when I use setViewportView to add it to a JScrollPane, a get an extended UI freeze—that operation takes several seconds. I'm trying to figure out what's taking so long. I've tried some fairly extreme things, like overriding the paintComponent, PaintComponents, paintChildren, paint, repaint, validate, revalidate, and validateTree methods in the panel with no-ops to try to figure out what's taking so long, but to no avail. I've tried validating the JPanel before adding it, but that has no effect. If I override the addImpl method of the scroll pane, that makes things quick, but it doesn't really narrow things down much.
View Replies
View Related
Sep 17, 2014
I am new to Java an have to Create a program that keeps track of the following information input by the user: First Name, Last Name, Phone Number, and Age. Now - let's store this in a multidimensional array that will hold 10 of these contacts. So our multidimensional array will need to be 10 rows and 4 columns.You should be able to add and remove contacts in the array.
View Replies
View Related
Sep 29, 2014
I have a controller that on the basis of commands (formaction and subaction) dispatch requests to different jsp pages. But somehow when I am debugging my application, I can find duplicate request coming to the controller, so one jsp page does load twice. I am not sure from where the duplicate request is generating.
View Replies
View Related
Feb 11, 2015
My program is supposed to be used to keep track of inventory for a company. The user is prompted with a menu that asks them which item they want to update and then gives them another menu that allows them to buy, sell, or change the price of the items. For this, I need to have the variable values to change (based on the input of the user), because they are initially set to specific numbers. How would I do this?
Here's the part of my code that is relevant to this question:
balance = 4000.00;
lampQuantity = 400;
lampPrice = 10;
chairQuantity = 250;
chairPrice = 20.00;
deskQuantity = 300;
deskPrice = 100.00;
System.out.println("Current Balance: $" + balance);
System.out.print("1. Lamps " + lampQuantity);
System.out.println(" at $" + lampPrice);
System.out.print("2. Chairs " + chairQuantity);
System.out.println(" at $" + chairPrice);
[Code] .....
View Replies
View Related
Apr 1, 2015
I have a TableView and it is scrolled to have some rows visible. Lets call the top visible row T, and the bottom one B.
I now replace the items in the TableView with a whole new list of items (so new data to view), but I want to scroll back to either T or B.
It seems to me that I have to somehow keep track of the topmost visible row, or the bottom-most visible row, but I can't figure out how to do that.
View Replies
View Related
Nov 1, 2014
So, I have this simple program that paints a string on JPanel using g2.drawString("Hello world", 40, 120). Basically, I want to be able to keep track of many strings on the JPanel at once. I'm not sure how to do this. For example, I would want to have an ArrayList of objects that keep track of these strings.
I want to be able to click-and-drag these strings so I will need to know there locations, etc.
Right now, using g2.drawString, it only draws the string. I want something like gw.draw(myStringObject).
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
[Code] .....
View Replies
View Related
Jan 28, 2014
I need to track the client IP address from where user requested to my application.
I tried following:
request.getHeader("HTTP_X_FORWARDED_FOR"));
request.getHeader("X-Forwarded-For"));
request.getHeader("Proxy-Client-IP"));
request.getHeader("WL-Proxy-Client-IP"));
request.getHeader("HTTP_CLIENT_IP"));
request.getHeader("HTTP_X_FORWARDED_FOR"));
request.getRemoteAddr());
String ip = InetAddress.getLocalHost().getHostAddress();
In which InetAddress is giving my local machine IP when i run my application in localhost, but I mapped localhost:8080 with IIS server then InetAddress not giving exact IP address. How can we resolve this?
View Replies
View Related