I have to test a web app and its API for UTF-8 strings.
Webapp has a text field and its API has corresponding getter method, I have to make sure UTF-8 will work, how do I do that?
I am trying to create a file using
File newFile = new File("myFile");
However no file called "myFile" is created. This is within a Web application Project i.e. proper form to be pakaged as a WAR but I am calling it as part of a main method (just to see how this works).
How can I make it so that a new file is created at a location relative to the current one i.e not have to put in an absolute path.
I want to read an input string and return it as a UTF8 encoded string. SO I found an example on the Oracle/Sun website that used FileInputStream. I didn't want to read a file, but a string, so I changed it to StringBufferInputStream and used the code below. The method parameter jtext, is some Japanese text. Actually this method works great. The question is about the deprecated code. I had to put @SuppressWarnings because StringBufferInputStream is deprecated. I want to know is there a better way to get a string input stream? Is it ok just to leave it as is? I've spent so long trying to fix this problem that I don't want to change anything now I seem to have cracked it.
@SuppressWarnings("deprecation")
private String readInput(String jtext) {
StringBuffer buffer = new StringBuffer();
try {
StringBufferInputStream sbis = new StringBufferInputStream (jtext);
InputStreamReader isr = new InputStreamReader(sbis,
"UTF8");
Reader in = new BufferedReader(isr);
int ch;
while ((ch = in.read()) > -1) {
buffer.append((char)ch);
}
in.close();
return buffer.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
I am looking at this piece of code. This constructor delegates to the native method "System.arraycopy"
Is it Thread safe? And by that I mean can it ever throw a ConcurrentModificationException?
public Collection<Object> getConnections(Collection<Object> someCollection) {
return new ArrayList<Object>(someCollection);
}
Does it make any difference if the collection being copied is ThreadSafe eg a CopyOnWriteArrayList?
public Collection<Object> getConnections(CopyOnWriteArrayList<Object> someCollection) {
return new ArrayList<Object>(someCollection);
}
Hi all,
I had an interview days ago and was thrown a question like this.
Q: Reverse a linked list. Following code is given:
public class ReverseList {
interface NodeList {
int getItem();
NodeList nextNode();
}
void reverse(NodeList node) {
}
public static void main(String[] args) {
}
}
I was confused because I did not know an interface object could be used as a method parameter. The interviewer explained a little bit but I am still not sure about this. Could somebody enlighten me?
I am new to JPA. I am cofused about the @Version annotation.
How it works?
I have googled it and found various answers whose extract is as follows:
JPA uses a version field in your entities to detect concurrent modifications to the same datastore record. When the JPA runtime detects an attempt to concurrently modify the same record, it throws an exception to the transaction attempting to commit last.
But still I am not sure how it works?
==================================================================================
Also as from the following lines:
You should consider version fields immutable. Changing the field value has undefined results.
Does it mean that we should declare our version field as final
Hi,
1) What is difference in thers two statements:
String s1 = "abc";
and
String s1 = new String("abc")
2) as i am not using new in first statement, how string object will be created
Thanks
I have a string which contains a contiguous chunk of digits and then a contiguous chunk of characters. I need to split them into two parts (one integer part, and one string).
I tried using String.split("\D", 1), but it is eating up first character.
I checked all the String API and didn't find a suitable method.
Is there any method for doing this thing?
I have two classes X and Y, like this:
class X implements Serializable
{
int val1;
Y val2;
}
class Y implements Serializable
{
int val;
}
I want to transmit an object of type X from a client to server but i can't because the class X has a field of type Y. I replace the field of type Y with a field of type X in class X and it works.
Need to write a method describePerson() that takes 3 parameters, a String giving a person’s
name, a boolean indicating their gender (true for female, false for male), and an integer giving their age. The method should return a String formatted as in the following examples:
Lark is female. She is 2 years old.
Or
Jay is male. He is 1 year old.
I am not sure how to write it correctly (my code):
int describePerson(String name, boolean gender, int age) {
String words="";
if(gender==true) return (name + "is "+gender+". "+"She is"+age+ "years old.);
else
return (name + "is "+gender+". "+"She is"+age+ "years old.);
}
The outcome "year" and "years" is also differs, but i don't know how to make it correct..
I'm having trouble understanding the following syntax:
public class SortedList< T extends Comparable< ? super T> > extends LinkedList< T >
I see that class SortedList extends LinkedList. I just don't know what
T extends Comparable< ? super T>
means.
My understanding of it so far is that type T must be a type that implements Comparable...but what is "< ? super T "?
I just set a conditional breakpoint in Eclipse's debugger with a mildly inefficient condition by breakpoint standards - checking whether a HashMap's value list (8 elements) contains Double.NaN. This resulted in an extremely noticeable slowdown in performance - after about five minutes, I gave up.
Then I copy pasted the condition into an if statement at the exact same line, put a noop in the if, and set a normal breakpoint there. That breakpoint was reached in the expected 20-30 seconds.
Is there something special that conditional breakpoints do that is different from this, or is Eclipse's implementation just kinda stupid? It seems like they could fairly easily just do exactly the same thing behind the scenes.
Hi,
I declared LinkedHashMap<String, float[]> and now I want to convert float[] values into double[][]. I am using following code.
LinkedHashMap<String, float[]> fData;
double data[][] = null;
Iterator<String> iter = fData.keySet().iterator();
int i = 0;
while (iter.hasNext()) {
faName = iter.next();
tValue = fData.get(faName);
//data = new double[fData.size()][tValue.length];
for (int j = 0; j < tValue.length; j++) {
data[i][j] = tValue[j];
}
i++;
}
When I try to print data System.out.println(Arrays.deepToString(data)); it doesn't show the data :(
I tried to debug my code and i figured out that I have to initialize data outside the
while loop but then I don't know the array dimensions :(
How to solve it?
Thanks
I am trying to use a simple split to break up the following string: 00-00000
My expression is: ^([0-9][0-9])(-)([0-9])([0-9])([0-9])([0-9])([0-9])
And my usage is:
String s = "00-00000";
String pattern = "^([0-9][0-9])(-)([0-9])([0-9])([0-9])([0-9])([0-9])";
String[] parts = s.split(pattern);
If I play around with the Pattern and Matcher classes I can see that my pattern does match and the matcher tells me my groupCount is 7 which is correct. But when I try and split them I have no luck.
Given an array of ints length 3, return a new array with the elements in reverse order, so {1, 2, 3} becomes {3, 2, 1}.
public int[] reverse3(int[] nums) {
int[] values = new int[3];
for(int i=0; i<=nums.length-1; i++) {
for(int j=nums.length-1; j>=0; j--) {
values[i]=nums[j];
}
}
return values;
}
I cant get this to work properly, usually the last int in the array, becomes every single int in the new array
So I have an application with a JFileChooser from which I select a file to read. Then I change some words and write a new file. The problem that I am having is that when I write the new file it's saved in the project directory. How do I save it in the same directory as the file that I chose using the JFileChooser. Note: I don't want to use the JFileChooser to choose the location. I just need to save the file in the same directory as the original file that I read.
I'm trying to print out debug statements when some third party code changes a variable. For example, consider the following:
public final class MysteryClass {
private int secretCounter;
public synchronized int getCounter() {
return secretCounter;
}
public synchronized void incrementCounter() {
secretCounter++;
}
}
public class MyClass {
public static void main(String[] args) {
MysteryClass mysteryClass = new MysteryClass();
// add code here to detect calls to incrementCounter and print a debug message
}
I don't have the ability to change the 3rd party MysteryClass, so I thought that I could use PropertyChangeSupport and PropertyChangeListener to detect changes to the secretCounter:
public class MyClass implements PropertyChangeListener {
private PropertyChangeSupport propertySupport = new PropertyChangeSupport(this);
public MyClass() {
propertySupport.addPropertyChangeListener(this);
}
public void propertyChange(PropertyChangeEvent evt) {
System.out.println("property changing: " + evt.getPropertyName());
}
public static void main(String[] args) {
MysteryClass mysteryClass = new MysteryClass();
// do logic which involves increment and getting the value of MysteryClass
}
}
Unfortunately, this did not work and I have no debug messages printed out. Does anyone see what is wrong with my implementation of the PropertyChangeSupport and Listener interfaces? I want to print a debug statement whenever incrementCounter is called or the value of secretCounter changes.
Suppose I have two methods in my classes, writeToMap() and processKey() and both methods are called by multiple threads. writeToMap is a method to write something in hashmap and processKey() is used to do sth based on the keySet of HashMap.
Inside processKey, I first copy the originalMap before getting the key set.
new HashMap<String, Map<String,String>(originalMap).get("xx").keySet();
But I am still getting ConcurrentModificationException even though I always copy the hashmap. Whats the problem?
I've got a Null Pointer Exception in my main that just won't go away and I'm totally out of ideas. The error is on the line "Board[x][y].color = 2;" in which Board is a public, static array of piece objects that contain instance variables like the one "color" that is being set to 2 in the above statement. Pieces is not static - that is there are many different copies of pieces, each with its own data, but only one board. The array has been initialized and defined as both public Piece[][] Board = new Piece[8][8] and public static Piece[][] Board = new Piece[8][8], but no matter how I mess around with it (getting rid of static, putting the variable in another object, etc.), I can't seem to get the error to go away. Help?
Is there a way to exit ('continue;') a loop iteration after a certain timeout period?
I have a loop that will run gathering data from the web and then use this data to make a calculation.
The data become obsolete after about 1 to 2 seconds so if the loop iteration takes longer than 1 second then i want it to 'continue' to the next iteration.
Sometimes gathering the data can take time but sometimes the calculation can take longer than 1 second so a HTTP timeout won't work for what i need.
Also, while doing the calculation the thread i am using is blocked so i cannot check System.currentTimeMillis();
Is there a way to use another Thread to check the time and force the original for loop to continue.
package Sartre.Connect4;
import javax.swing.*;
public class ChatGUI extends JDialog {
public ChatGUI(){
setTitle("Chat");
}
}
when i do this in another class in the same package:
ChatGUI chatGUI = new ChatGUI();
i end up with a situation: Cannot Find Symbol
please help?
In which cases should I use this way:
public A clone() throws CloneNotSupportedException {
A clone = (A)super.clone();
clone.x= this.x;
return clone;
}
And in which cases should I use that way:
public ShiftedStack clone() throws CloneNotSupportedException {
return new A(this.x);
}
What should I do if x is final and I want to use the first way?
Regarding the first way, I understand it like this: we clone the super class and up-cast it, leading to some members uninitialized. After this initialize these members. Is my understanding correct?
Thank you.
Hi,
could u give me a sample code of using output parameter in function? I tried to google it but just found it in function. I'd like to use this output value in another function.
I will use this code in Android.