 |
 |
Index ‹ java-programmer
|
- Previous
- 1
- 1
- design problem: visitor/multiple dispatch or?Greetings and salutations,
I'm struggling with a bit of a mess (solely created by me and myself).
Suppose a bunch of types (classes) exist, say, T_1, T_2, ... T_n, implementing
a single interface or inheriting from some (abstract) base class T. Also assume
that some 'applicators' exit, say, A_1, A_2 ... Am, all implementing an interface
(or abstract base class) equivalent to --
interface Applicator {
Object apply(T ta, T tb);
}
If both sets T_i and A_j are 'fixed', i.e no new classes T_p nor A_q enter
my messy arena, I could implement all A_i as visitors to the T_j classes
in order to get their job done. OTOH, all T_j classes could double dispatch
the 'A_i.apply' methods to their T_j counterparts to get the job done.
I realise that some form of a Cartesian product of 'apply' methods must
reside somehwere, somehow ...
For the sake of the example, think of the T_j as being subclasses of classes
Short, Int, Long, Double, and let the Appliers be something like 'Add', 'Sub'
etc. i.e. the folllowing code snippet should make sense --
Add myAdd= new Add();
Dbl myDbl= new Dbl(41);
Int myInt= new Int(1);
// assume Num is a superclass of Dbl and Int
Num total= myAdd.apply(myDbl, myInt);
Variable 'total' should have type 'Dbl' in this example. As I wrote above,
there would be no problem if at least set T_j would be fixed; the visitor
pattern would do fine. If set A_i would be fixed the multiple dispatch
pattern (over the set T_j) would be a fine fit. But what to do if both sets
may be expanded?
I've fiddle-diddled with introspection, synthesizing class names given a T_i
and T_j, caching them in hashmaps but to no avail -- my code is a mess and
my design is something I'm ashamed off. I would really appreciate it if
some kind soul here could enlighten me.
TIA, and kind regards,
Jos
- 1
- how to draw ER and UML diagram in eclipse?what free eclipse plugin do you use to draw database ER diagram and
UML diagrams?
I've tried omondo years ago, it leaks memory so bad back then and
always crash my eclipse, is it getting better now?
- 2
- Telephonic CredentialsI think it would be nice if I could prove to someone on the other end
of the phone I am me, and demand they prove they are who they claim to
be.
It could be done by letting a modem kick in for a second to exchange
challenge phrases to be encrypted by identification certificate that
might include name, address, phone number, expiry date, company.
Then if some charity I donate to phone me, I can be sure it is them.
There are so many scams out there.
It might also be done by each of us contacting an Internet server.
Has anyone heard of such projects?
--
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
- 2
- Thoughts on Code reviewI need some advice guys.. I am proposing that we get someone to do a
complete audit/review of our Java application codebase, about 1000
JSPs/Servlets and 100 EJBs. If I get firms to submit proposals, what
should I be asking /looking out for? I realise that running the
applications through a migration tool will help but I am looking for a
more through analysis of the actual codebase as well as assessment of
the architecture
Thanks
Arvie
- 2
- hi friends.please helpI am trying t make a jTable Using Abstract TableModel. But my JTable
doesnot appear on the frame.I have written two classes myTable and
jTable2 .My code is given below:
import javax.swing.*;
import java.awt.*;
public class myTable {
public static void main(String args[]){
JTable2 tbl2=new JTable2();
JTable aTbl=new JTable(tbl2);
aTbl.updateUI();
aTbl.setVisible(true);
JFrame frame=new JFrame("Jtable using AbstractTableModel");
JPanel pan=new JPanel();
JScrollPane scp=new JScrollPane();
scp.add(aTbl);
pan.add(scp);
frame.getContentPane().add(pan);
frame.setVisible(true);
frame.pack();
}
}
import javax.swing.*;
import java.sql.*;
import java.util.*;
import javax.swing.table.*;
public class JTable2 extends AbstractTableModel{
Connection con;
Statement stmt;
ResultSet rs;
int columns;
Vector allRows;
Vector row=new Vector();
String [] columnNames={"ID_CODE","NAME","SECTION"};
public JTable2(){
// connect to database
try{
db_connect();
getData();
}catch(Exception ex){
ex.printStackTrace();
}
}
void db_connect() throws SQLException{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@158.144.71.242:1521:dbadp","payroll","sush");
System.out.println("Connected");
}catch(Exception ex){
ex.printStackTrace();
}
}
void getData() throws SQLException {
try{
stmt=con.createStatement();
rs=stmt.executeQuery("select idcode,id_name,sec_code from
employee");
ResultSetMetaData rsMetaData=rs.getMetaData();
columns=rsMetaData.getColumnCount();
allRows=new Vector();
while(rs.next()){
Vector newRow=new Vector();
for(int i=1;i<=columns;i++){
newRow.addElement(rs.getObject(i));
}
allRows.addElement(newRow);
}
}catch (Exception ex){
ex.printStackTrace();
}
}
public int getRowCount(){
return allRows.size();
}
public int getColumnCount(){
return columns;
}
public Object getValueAt(int aRow,int aColumn){
row=(Vector) allRows.elementAt(aRow);
return row.elementAt(aColumn);
}
public boolean isCellEditable(int row, int col){
return false;
}
}
- 6
- truncating java doublesHi,
How do you truncate java doubles? I am trying to convert a double to a
number thats rounded to 3 decimal places - i can do this using BigDecimals
easily but cant seem to find anything to do the same with a double.
Thanks
- 6
- Serializable : readObject and writeObjectHello,
I have 3 classes Personne, entreeb==>FileInputStream ,
sortieb==>FileOutputStream.
The code works one time. The problem is when I add serialized new objects
( launch again the code sortieb) I can't read all objects (entreeb) specific
a new objects added.
have you an idea?
Thanks form help
-----------------------------------------------------------
-----------------------------------------------------------
//Class Personne
import java.io.*;
class Personne implements Serializable {
private String nom;
private int age;
public Personne(String n, int a){
nom = n;
age = a;
}
public void aff() {
System.out.println (nom + " " + age);
}
}
------------------------------------------------
//Flux in
import java.io.*;
import java.util.*;
public class entreeb {
public static void main(String[] args){
Personne p;
int i=0;
try {
FileInputStream fist= new FileInputStream("Personne.ser");
ObjectInputStream oist = new ObjectInputStream(fist);
try {
while (true)
{ System.out.println("i="+i);
p = (Personne) oist.readObject();
p.aff();
i++;
}
} catch (EOFException e) { }
oist.close();
} catch (Exception e) {
System.out.println("Exception loading personne : " + e.getMessage());
}
}
}
------------------------------------------------------------------
//Flux out
import java.io.*;
import java.util.*;
public class sortieb {
public static void main(String[] args) throws IOException {
Personne p = new Personne("name", 55);
File f=new File("Personne.ser");
FileOutputStream fost= new FileOutputStream(f,true);
ObjectOutputStream oost = new ObjectOutputStream(fost);
int i=0;
while (i<5) {
System.out.println("i = "+i+ "p="+p);
oost.writeObject(p);
i+=1;
}
oost.close();
}
}
- 7
- Client application using Weblogic JMS ServerHello, I'm Jose from Barcelona,
I'm not at all expert on JMS, and my question is about how can I
connect a client application running java with a remote JMS Weblogic
Server. I've developed a client program and tested it with a Sun J2EE
server running on a XP box, but the goal is to make it run on an
iSeries machine connecting a WebLogic JMS Server.
My questions are:
Do I have to install some application software on the client box?
Is there any difference between connection with remote JMS servers and
connection with local ones?.
I hope you can help me.
Thank You.
- 7
- Animation ProblemLew wrote:
> James Sarjeant wrote:
>> Thank you so much everyone, it worked with the javax.swing.Timer events.
>> Still got other bugs to iron out but thats a huge hurdle overcome.
>> Thanks again
>
> Remember: you think you have gotten away from the advice about the EDT,
> but you haven't.
>
It's a pesky thing isn't it :-).
--
Knute Johnson
email s/nospam/knute/
- 8
- drag and drop in a JMenu/JMenuItem
Can someone please point me to some sample code that allows drag and
drop in a JMenu/JMenuItem. I know that Java doesn't support dnd in
the menu stuff, but I need it anyway. Technically speaking it doesn't
have to be a popup menu, but would be nice, as long as it has the look
and feel of a popup menu (i.e. fonts, size, etc.). An example of what
I'm talking about, via menus, is the start menu under Windows. Those
menus allow you to do dnd, but of course it's Windows and they allow
anything and everything. Just to note I'm using JDK 1.5.x if that
helps for the code direction.
- 13
- Newbie question - reading delimited files and printing...Reading files - pipe delimited or comma delimeted...
Searching for a element in one field and then showing certain fields where
element is in line.
eg...
HEHE|HI|ME|2.5
JOKE|HELLO|YOU|3.4
DONT|HI|YOU|3.4
I want all rows with YOU in second column and I want to print out 2nd and
4th columns.
SO, my answer would be
HI 2.5
HI 3.4
...
Next question...
same list only a datestamp on the end...
HEHE|HI|ME|2.5|20031223091234
JOKE|HELLO|YOU|3.4|20031223091245
DONT|HI|YOU|3.4|20031223091247
....
1) I want all rows with YOU in second column and I want to print out 2nd and
4th columns in the 09:00:00 - 09:59:59 time frame.
2) I want an average of response time(4th field).
3) I want an average of response time broken down by hour.
Can someone help with all of this?
Please email to my home email (feel free to copy here).
email***@***.com
take out the _no_spam_
Thanks,
Markis
- 14
- Debugging API classes in NetbeansWhen Im debugging my program in Netbeans, and I try to debug into API
(e.g. Swing JPanel) the debugger tells me that the source of the class
has not been found in mounted filesystem. Even though
c:\j2sdk1.4.2_02\src.jar is indeed mounted.
How do I debug into API classes?
Thanxxxx,
Barsum
- 14
- Inidicator Arrow convention for Sort OrderWhich way should an arrow point to indicate an ascending sort or an
ascending list follows?
For an ascending sort the bigger numbers are at the bottom.
So no matter which way you do it, you can misinterpret.
Is there some other less ambiguous convetion to use?
--
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
- 15
- Check for time functionHello all...I have an issue with one of my java script functions that
I'm hoping someone can easily help with. I have a web based application
that we use to create/sign up for overtime. When we have holidays we
require our employees to sign up in 4 hr increments for the times we
post. I'm having trouble creating a time slot that ends @ 12am. 12pm
and all other hours work fine for start/end times. however 12am causes
problems. My actual script code for this function is below. Someone
help!!!
<SCRIPT language="JavaScript" src="frmvalidation.js"
type="text/JavaScript"></SCRIPT>
<script language="javascript">
function checkValidHoliday(value)
{
if (value=='Y'){
hourblock.style.visibility ='visible';
}
else{
hourblock.style.visibility ='hidden';
}
}
function checkHoliday(frm)
{
if(frm.txtIsHoliday.value=="Y")
{
strFromDt= new Date(frm.txtLimitDate.value);
strToDt= new Date(frm.txtLimitToDate.value);
FromHr=parseInt(frm.txtLimitFrom.value);
FromAMPM=frm.txtLimitFromAM_PM.value;
ToHr=parseInt(frm.txtLimitTo.value);
ToAMPM=frm.txtLimitToAM_PM.value;
if((FromAMPM=="PM") && (FromHr!=12))
FromHr=FromHr+12;
if((ToAMPM=="PM") && (ToHr!=12))
ToHr=ToHr+12;
var fromDt= new
Date(strFromDt.getFullYear(),strFromDt.getMonth(),strFromDt.getDate(),FromHr,0);
var toDt= new
Date(strToDt.getFullYear(),strToDt.getMonth(),strToDt.getDate(),ToHr,0);
//alert(toDt + " " + fromDt);
//alert(FromHr + " " +ToHr);
var HolidayBlock=(parseInt(frm.cboHolidayHours.value) * 360 * 10000)
;
//alert((toDt-fromDt) + " " + HolidayBlock );
if((toDt-fromDt)== HolidayBlock)//14400000)
return true;
else
{
alert("Please select "+ parseInt(frm.cboHolidayHours.value) +" Hour
Block only for Holiday!");
frm.txtLimitFrom.focus();
return false;
}
}
return true;
}
</script>
|
| Author |
Message |
zero

|
Posted: 2005-11-4 23:44:00 |
Top |
java-programmer, stupid generics
When I first heard about generics I was excited. A great idea finally
available in Java. But the way they are implemented really makes no sense.
Because of type erasure generics do nothing that 1.4 code didn't already do
by using Object as "generic" class for all (sub)classes.
And the problem with arrays of generic classes? Simply ridiculous. There
is no sane reason why the following code (from a self-learning chess
program I've been working on) should not work, and yet...
ArrayList<Piece>[] board;
board = new ArrayList<Piece>[8]; // error: cannot create a generic
// array of ArrayList<Piece>
board[0] = new ArrayList<Piece>();
board[0].add(0, new Rook(false, 0, 8));
where of course Rook is a subclass of Piece.
I'm forced to use board = new ArrayList[8]; which of course gives an
unchecked warning.
They should just throw away the whole generics thing and replace it with a
C++ like approach.
|
| |
|
| |
 |
Daniel Dyer

|
Posted: 2005-11-4 23:59:00 |
Top |
java-programmer >> stupid generics
On Fri, 04 Nov 2005 15:43:59 -0000, zero <email***@***.com> wrote:
> And the problem with arrays of generic classes? Simply ridiculous.
> There
> is no sane reason why the following code (from a self-learning chess
> program I've been working on) should not work, and yet...
>
> ArrayList<Piece>[] board;
> board = new ArrayList<Piece>[8]; // error: cannot create a generic
> // array of ArrayList<Piece>
> board[0] = new ArrayList<Piece>();
> board[0].add(0, new Rook(false, 0, 8));
>
> where of course Rook is a subclass of Piece.
>
> I'm forced to use board = new ArrayList[8]; which of course gives an
> unchecked warning.
I share your frustration with the difficulty in creating a generic array
(it is possible with the java.lang.reflect.Array.newInstance method and an
unchecked cast), but why not model the board as a two dimensional array of
pieces?
Piece[][] board = new Piece[8][8];
Dan.
--
Daniel Dyer
http://www.dandyer.co.uk
|
| |
|
| |
 |
zero

|
Posted: 2005-11-5 0:15:00 |
Top |
java-programmer >> stupid generics
"Daniel Dyer" <email***@***.com> wrote in
news:email***@***.com:
>
> I share your frustration with the difficulty in creating a generic
> array (it is possible with the java.lang.reflect.Array.newInstance
> method and an unchecked cast), but why not model the board as a two
> dimensional array of pieces?
>
> Piece[][] board = new Piece[8][8];
>
> Dan.
>
To be honest I don't remember why I chose the array of arraylists. I wrote
this code over a year ago, but then other things got in the way and the
project was postponed. I just started cleaning up the code to move to 1.5
and continue development.
I guess a board doesn't change size, so there's no real point in using
arraylists. I may indeed change it, thanks for pointing it out.
Doesn't change the fact that generics are stupid though ;-)
|
| |
|
| |
 |
Daniel Dyer

|
Posted: 2005-11-5 0:18:00 |
Top |
java-programmer >> stupid generics
On Fri, 04 Nov 2005 15:59:24 -0000, Daniel Dyer
<email***@***.com> wrote:
> it is possible with the java.lang.reflect.Array.newInstance method and
> an unchecked cast
I don't know why I made that so complicated, it's just equivalent to this:
ArrayList<Piece>[] board = (ArrayList<Piece>[]) new ArrayList[8];
You will get a warning (which you can suppress with the @SuppressWarnings
annotation, or at least you will be able to once it is implemented
properly in 1.6), but at leat you will get compile-time type checking on
subsequent operations involving the generic list.
Dan.
--
Daniel Dyer
http://www.dandyer.co.uk
|
| |
|
| |
 |
Roedy Green

|
Posted: 2005-11-5 17:53:00 |
Top |
java-programmer >> stupid generics
On Fri, 04 Nov 2005 15:43:59 GMT, zero <email***@***.com> wrote, quoted or
indirectly quoted someone who said :
>board = new ArrayList<Piece>[8]; // error: cannot create a generic
> // array of ArrayList<Piece>
ArrayList uses () not [] to define the size.
--
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
|
| |
|
| |
 |
Roedy Green

|
Posted: 2005-11-5 17:55:00 |
Top |
java-programmer >> stupid generics
On Fri, 04 Nov 2005 15:43:59 GMT, zero <email***@***.com> wrote, quoted or
indirectly quoted someone who said :
> board = new ArrayList[8];
this means you want 8 ArrayLists, not an ArrayList of 8 elements. Is
that what you meant?
If you did want 8 ArrayLists, you still have initialise each of the 8
slots with an ArrayList object.
See http://mindprod.com/jgloss/gotchas.html#ARRAY
--
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
|
| |
|
| |
 |
Roedy Green

|
Posted: 2005-11-5 18:00:00 |
Top |
java-programmer >> stupid generics
On Fri, 04 Nov 2005 15:43:59 GMT, zero <email***@***.com> wrote, quoted or
indirectly quoted someone who said :
>board = new ArrayList<Piece>[8]; // error: cannot create a generic
For a chessboard, you have precisely 8 row and 8 columns. That will
never change. Therefore you should use an array not an ArrayList of
ArrayLists. It is much simpler code.
Piece[][] board = new Piece[8][8];
for ( int row=0; row<8; row++ )
{
for ( int col=0; col<8; col++ )
{
board[row][col] = new Piece();
}
}
You don't need generics with arrays. Typing in built in properly.
--
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
|
| |
|
| |
 |
zero

|
Posted: 2005-11-6 0:03:00 |
Top |
java-programmer >> stupid generics
Roedy Green <email***@***.com> wrote in
news:email***@***.com:
> On Fri, 04 Nov 2005 15:43:59 GMT, zero <email***@***.com> wrote, quoted or
> indirectly quoted someone who said :
>
>>board = new ArrayList<Piece>[8]; // error: cannot create a generic
>
> For a chessboard, you have precisely 8 row and 8 columns. That will
> never change. Therefore you should use an array not an ArrayList of
> ArrayLists. It is much simpler code.
>
> Piece[][] board = new Piece[8][8];
>
> for ( int row=0; row<8; row++ )
> {
> for ( int col=0; col<8; col++ )
> {
> board[row][col] = new Piece();
> }
> }
>
> You don't need generics with arrays. Typing in built in properly.
>
Yes, Dan pointed that out already too. See my reply to his post.
|
| |
|
| |
 |
zero

|
Posted: 2005-11-6 0:03:00 |
Top |
java-programmer >> stupid generics
Roedy Green <email***@***.com> wrote in
news:email***@***.com:
> On Fri, 04 Nov 2005 15:43:59 GMT, zero <email***@***.com> wrote, quoted or
> indirectly quoted someone who said :
>
>> board = new ArrayList[8];
> this means you want 8 ArrayLists, not an ArrayList of 8 elements. Is
> that what you meant?
>
> If you did want 8 ArrayLists, you still have initialise each of the 8
> slots with an ArrayList object.
>
> See http://mindprod.com/jgloss/gotchas.html#ARRAY
>
Hence the next line in my code:
board[0] = new ArrayList<Piece>();
Obviously this is part of a for loop, I just slimmed down the code. That
was not really the point of my post anyway. The point was, it is
*impossible* to create an array of parameterized types without getting a
warning.
|
| |
|
| |
 |
Thomas Hawtin

|
Posted: 2005-11-6 3:54:00 |
Top |
java-programmer >> stupid generics
Roedy Green wrote:
> On Fri, 04 Nov 2005 15:43:59 GMT, zero <email***@***.com> wrote, quoted or
> indirectly quoted someone who said :
>
>
>>board = new ArrayList<Piece>[8]; // error: cannot create a generic
>
>
> For a chessboard, you have precisely 8 row and 8 columns. That will
> never change. Therefore you should use an array not an ArrayList of
> ArrayLists. It is much simpler code.
Might want to use the code for Go boards as well. Perhaps.
I would tend to make the Board a class itself, and slightly optimise/get
rid of the array of arrays confusion. (A List would do in place of the
array.)
private int index(int row, int col) {
if (!(
0 <= row && row < size &&
0 <= col && col < size
)) {
throw new IllegalArgumentException();
}
return row*size + col;
}
public Piece get(int row, int col) {
return board[index(row, col)];
}
> You don't need generics with arrays. Typing in built in properly.
Generics is a built in property of arrays. You don't need arrays of
generics.
Tom Hawtin
--
Unemployed English Java programmer
http://jroller.com/page/tackline/
|
| |
|
| |
 |
Googmeister

|
Posted: 2005-11-6 4:12:00 |
Top |
java-programmer >> stupid generics
Thomas Hawtin wrote:
> Generics is a built in property of arrays. You don't need arrays of
> generics.
I'm not sure I follow. I agree the OPs example was poor motivation,
but many of us would very much like to be able to create arrays of
generics, e.g., array implementation of a stack.
|
| |
|
| |
 |
Thomas G. Marshall

|
Posted: 2005-11-6 13:07:00 |
Top |
java-programmer >> stupid generics
Thomas Hawtin coughed up:
> Roedy Green wrote:
...[rip]...
>> You don't need generics with arrays. Typing in built in properly.
>
> Generics is a built in property of arrays. You don't need arrays of
> generics.
That doesn't make any sense to me at all. In this example:
ArrayList<Apple>[] allGroves = new ArrayList<Apple>[100];
I would be asking for an array of ArrayLists's that each only take Apples.
This would prevent someone from doing this by accident later:
allGroves[50] = new ArrayList<Orange>();
Regardless of whether or not the OP has modeled his particular issue
correctly, not having this ability seems an annoyance that /might/ not have
been necessary.
--
With knowledge comes sorrow.
|
| |
|
| |
 |
Thomas Hawtin

|
Posted: 2005-11-6 14:01:00 |
Top |
java-programmer >> stupid generics
Thomas G. Marshall wrote:
> Thomas Hawtin coughed up:
>
>>Roedy Green wrote:
>
>
> ...[rip]...
>
>
>>>You don't need generics with arrays. Typing in built in properly.
>>
>>Generics is a built in property of arrays. You don't need arrays of
>>generics.
>
>
>
> That doesn't make any sense to me at all. In this example:
>
> ArrayList<Apple>[] allGroves = new ArrayList<Apple>[100];
>
> I would be asking for an array of ArrayLists's that each only take Apples.
> This would prevent someone from doing this by accident later:
>
> allGroves[50] = new ArrayList<Orange>();
>
> Regardless of whether or not the OP has modeled his particular issue
> correctly, not having this ability seems an annoyance that /might/ not have
> been necessary.
What I was trying to say (extremely badly) is that arrays fit in with
the concept of genericity in that they have the property of being
generic. Unfortunately they do it with different (and less safe rules)
than the rest of the language. Once we have something the wraps arrays,
then the only real need for arrays of references is for optimisation.
Mixing the two is just an annoyance.
Tom Hawtin
--
Unemployed English Java programmer
http://jroller.com/page/tackline/
|
| |
|
| |
 |
Roedy Green

|
Posted: 2005-11-6 15:45:00 |
Top |
java-programmer >> stupid generics
On 5 Nov 2005 12:11:45 -0800, "Googmeister" <email***@***.com>
wrote, quoted or indirectly quoted someone who said :
>> Generics is a built in property of arrays. You don't need arrays of
>> generics.
>
>I'm not sure I follow.
With ArrayList you use <Thing> notation to tell the compiler what sort
of beasts will live in the ArrayList. With plain arrays, you just use
Thing[] without that notation. You sidestep all the quirky generics
issues of type erasure etc. With arrays, the typing is built in
properly rather than hacked with generics.
--
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
|
| |
|
| |
 |
Googmeister

|
Posted: 2005-11-6 19:17:00 |
Top |
java-programmer >> stupid generics
Roedy Green wrote:
> On 5 Nov 2005 12:11:45 -0800, "Googmeister" <email***@***.com>
> wrote, quoted or indirectly quoted someone who said :
>
> >> Generics is a built in property of arrays. You don't need arrays of
> >> generics.
> >
> >I'm not sure I follow.
>
> With ArrayList you use <Thing> notation to tell the compiler what sort
> of beasts will live in the ArrayList. With plain arrays, you just use
> Thing[] without that notation. You sidestep all the quirky generics
> issues of type erasure etc. With arrays, the typing is built in
> properly rather than hacked with generics.
OK, I see. To me "array of generics" refers to what you want to
do when you implement an ArrayList (or any other array-based
data structure).
public class ArrayList<Item> {
private Item[] elements; // error: "can't create an array of
generics"
...
I'd very much like to do this. Generics are particularly useful with
collections and other data structures, but the language gets in your
way if you try to create your own.
|
| |
|
| |
 |
Roedy Green

|
Posted: 2005-11-6 20:07:00 |
Top |
java-programmer >> stupid generics
On 6 Nov 2005 03:17:21 -0800, "Googmeister" <email***@***.com>
wrote, quoted or indirectly quoted someone who said :
>public class ArrayList<Item> {
> private Item[] elements; // error: "can't create an array of
>generics"
I wrote a little program to confirm this to myself:
import java.util.ArrayList;
/**
* explore use of Generics and arrays
*/
public class GenAr
{
/**
* test harness
*
* @param args not used
*/
public static void main ( String[] args )
{
ArrayList<String>[] stuff = new ArrayList<String>[ 10 ];
}
}
I feel embarrassed that Java's generics are so Mickey Mouse they don't
even integrate with arrays.
--
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
|
| |
|
| |
 |
zero

|
Posted: 2005-11-6 20:31:00 |
Top |
java-programmer >> stupid generics
"Thomas G. Marshall"
<email***@***.com> wrote in
news:icgbf.2927$SV1.475@trndny01:
> Thomas Hawtin coughed up:
>> Roedy Green wrote:
>
> ...[rip]...
>
>>> You don't need generics with arrays. Typing in built in properly.
>>
>> Generics is a built in property of arrays. You don't need arrays of
>> generics.
>
>
> That doesn't make any sense to me at all. In this example:
>
> ArrayList<Apple>[] allGroves = new ArrayList<Apple>[100];
>
> I would be asking for an array of ArrayLists's that each only take
> Apples. This would prevent someone from doing this by accident later:
>
> allGroves[50] = new ArrayList<Orange>();
>
> Regardless of whether or not the OP has modeled his particular issue
> correctly, not having this ability seems an annoyance that /might/ not
> have been necessary.
>
The generics tutorial(1) gives a reason for this annoyance, however I think it
could all have been sidestepped by a better implementation for generics.
<disclaimer>
Following code is NOT Java, but is the way I wish it would work. (based on the
way templates are implemented in C++)
</disclaimer>
Take generic class GenericContainer, with type parameter T:
public class GenericContainer<T>
{
T[] data;
public GenericContainer(int size)
{
data = new T[size];
}
public T get(int index)
{
return data[index];
}
// ...
}
When you use this class, for example;
GenericContainer<MyClass> c = new GenericContainer<MyClass>(5);
the compiler should generate a GenericContainerOfMyClass class, which would be:
public class GenericContainerOfMyClass
{
MyClass[] data;
public GenericContainerOfMyClass(int size)
{
data = new MyClass[size];
}
public MyClass get(int index)
{
return data[index];
}
// ...
}
Thus a different class would be created for each type of GenericContainer you
want.
This would greatly improve things. The way generics are implemented now I see
only 2, very minor, advantages over 1.4 code: the compiler checks the type, and
you don't have to typecast when for example getting an object from a collection.
(1) http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
|
| |
|
| |
 |
zero

|
Posted: 2005-11-6 20:57:00 |
Top |
java-programmer >> stupid generics
Roedy Green <email***@***.com> wrote in
news:email***@***.com:
>
> I feel embarrassed that Java's generics are so Mickey Mouse they don't
> even integrate with arrays.
That almost sounds like an insult to Mickey Mouse ;-)
|
| |
|
| |
 |
Ross Bamford

|
Posted: 2005-11-6 22:30:00 |
Top |
java-programmer >> stupid generics
On Sun, 06 Nov 2005 12:30:55 -0000, zero <email***@***.com> wrote:
> "Thomas G. Marshall"
> <email***@***.com> wrote in
> news:icgbf.2927$SV1.475@trndny01:
>
>> ...[rip]...
>>
>> That doesn't make any sense to me at all. In this example:
>>
>> ArrayList<Apple>[] allGroves = new ArrayList<Apple>[100];
>>
>> I would be asking for an array of ArrayLists's that each only take
>> Apples. This would prevent someone from doing this by accident later:
>>
>> allGroves[50] = new ArrayList<Orange>();
>>
>> Regardless of whether or not the OP has modeled his particular issue
>> correctly, not having this ability seems an annoyance that /might/ not
>> have been necessary.
>>
>
> The generics tutorial(1) gives a reason for this annoyance, however I
> think it
> could all have been sidestepped by a better implementation for generics.
>
> [ ... ]
> (1) http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
>
Hmm, that's interesting. In that, they give the reason for avoiding this
kind of thing as
"This restriction is necessary to avoid situations like:
List<String>[] lsa = new List<String>[10]; // not really allowed
Object o = lsa;
Object[] oa = (Object[]) o;
List<Integer> li = new ArrayList<Integer>();
li.add(new Integer(3));
oa[1] = li; // unsound, but passes run time store check
String s = lsa[1].get(0); // run-time error - ClassCastException
If arrays of parameterized type were allowed, the example above would
compile without any unchecked warnings, and yet fail at run-time."
Perhaps it's just me, but I don't really see much difference between that
and:
List<String> lsa = new ArrayList<String>(); // ... but this is.
Object o = lsa;
Object[] oa = (Object[]) o;
List<Integer> li = new ArrayList<Integer>();
li.add(new Integer(3));
oa[1] = li; // still unsound, and *no* runtime store check
String s = lsa.get(0); // run-time error - ClassCastException
Have I missed something, or is it just a pretty poor excuse. If the
compiler couldn't check array access at all then I could understand the
reasoning, but it can - I just can't see any real barriers that prevent
generic array instantiation. What am I missing?
--
Ross Bamford - email***@***.com
|
| |
|
| |
 |
Ross Bamford

|
Posted: 2005-11-6 23:24:00 |
Top |
java-programmer >> stupid generics
On Sun, 06 Nov 2005 12:30:55 -0000, zero <email***@***.com> wrote:
> <disclaimer>
> Following code is NOT Java, but is the way I wish it would work. (based
> on the
> way templates are implemented in C++)
> </disclaimer>
>
> Take generic class GenericContainer, with type parameter T:
>
> public class GenericContainer<T>
> {
> T[] data;
>
> public GenericContainer(int size)
> {
> data = new T[size];
> }
>
> public T get(int index)
> {
> return data[index];
> }
>
> // ...
> }
>
> When you use this class, for example;
>
> GenericContainer<MyClass> c = new GenericContainer<MyClass>(5);
>
> the compiler should generate a GenericContainerOfMyClass class, which
> would be:
>
> public class GenericContainerOfMyClass
> {
> MyClass[] data;
>
> public GenericContainerOfMyClass(int size)
> {
> data = new MyClass[size];
> }
>
> public MyClass get(int index)
> {
> return data[index];
> }
>
> // ...
> }
>
> Thus a different class would be created for each type of
> GenericContainer you
> want.
I think the current system achieves a reasonable balance between
flexibility on the one hand, and performance and backward compatibility on
the other. I'm not saying it's perfect (*far* from it), but I think that
if they had gone the bytecode-generation route it would have been a lot
less useful - an unrestricted number of new classes being generated on the
fly, entirely 'under the hood' (i.e. outside your app's control). It might
make even basic operations entirely unpredictable in terms of time,
compromise security, and make it much more difficult to implement custom
classloading strategies. I expect it's likely that the generics team
started with something like above, given that bytecode generation is used
elsewhere in the platform, and then worked backward to try to make it
performant and compatible.
>
> This would greatly improve things. The way generics are implemented now
> I see
> only 2, very minor, advantages over 1.4 code: the compiler checks the
> type, and
> you don't have to typecast when for example getting an object from a
> collection.
>
I think generics are a great convenience for working with collections, and
useful in other situations too. I think the problem is more that they
promise too much - it's natural to assume you can do things like
T.newInstance() and new List<String>[40]. Erasure is certainly a minefield
of ifs and elses, but I'm not convinced that creating separate classes
under the hood is a viable alternative.
--
Ross Bamford - email***@***.com
|
| |
|
| |
 |
Googmeister

|
Posted: 2005-11-7 0:46:00 |
Top |
java-programmer >> stupid generics
Ross Bamford wrote:
> > The generics tutorial(1) gives a reason for this annoyance, however I
> > think it
> > could all have been sidestepped by a better implementation for generics.
My understanding is that the underlying reason is that arrays are
"covariant" but generics are not. In other words, String[] is a subtype
of
Comparable[], but List<String> is not a subtype of List<Comparable>.
In a world without generics, covariant arrays are useful, e.g., to
implement Arrays.sort(Comparable[]) and have it be callable with an
input of type String[]. But now that Java has generics, the usefulness
of covariant arrays is diminished, but we are stuck with them.
|
| |
|
| |
 |
| |
 |
Index ‹ java-programmer |
- Next
- 1
- reinventing the wheelhttp://www.ted.com/index.php/talks/view/id/162
This is off topic, but Java folk will like find it amusing. It shows
a Dutch invention to replace the wheel, various mechanical walking
machines. It has a mechanical step counter, a sort of primitive finite
state automaton..
--
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
- 2
- writing email attachment file to diskI'm trying to capture an email attachment and write it to disk.
I've coded the following lines in my attempt. The program seems
to run and creates the local file alex99.pdf. However, when I
tried to open it, it says it's corrupted and/or wasn't properly
decoded. Any ideas?
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("pop3");
store.connect(host, username, password);
Folder folder = store.getFolder("inbox");
folder.open(Folder.READ_ONLY);
Message message[] = folder.getMessages();
for (int i = 0, n = message.length; i < n; i++) {
System.out.println(i + ": " + message[i].getFrom() + "\t"
+ message[i].getSubject());
Object obj = message[i].getContent();
if (obj instanceof String) {
System.out.println(">>>plain text");
} else if (obj instanceof Multipart) {
System.out.println("Multipart");
Multipart mp = (Multipart) obj;
System.out.println("mp count = " + mp.getCount());
for (int j = 0, nn = mp.getCount(); j < nn; j++) {
Part part = mp.getBodyPart(j);
String disposition = part.getDisposition();
if ((disposition != null)&& ((disposition.equals(Part.ATTACHMENT) ||
(disposition.equals(Part.INLINE))))) {
System.out.println("attachment");
FileOutputStream fos = new FileOutputStream("alex99.pdf");
part.writeTo(fos);
} else if (disposition==null) {
MimeBodyPart mbp = (MimeBodyPart)part;
if (mbp.isMimeType("text/plain")) {
System.out.println("text/plain");
} else {
System.out.println("other mime type");
}................................
- 3
- Choosing elements to display in a JSP using StrutsHello,
I am very new to everything web development, so please bear with me.
My development environment is:
Win2k
Tomcat 4.0.30
Apache 2.0.48
mod_jk/2.0.4
j2sdk 1.4.2
Struts 1.1
mysql 4.0.18
I am using Struts to develop my webapp in an MVC fashion. I am using
forms based authentication to a mysql database.
Using the tools in my development environment, I am wondering if it is
possible to choose the elements displayed in a JSP based on the group
the user is in (and still stay withing the MVC framework), or if that
is even the right approach. I prefer to not show options to users if
they do not have permissions to perform them.
Any suggestions or advice would be great. If you know of any
tutorials/books/web resources that you could point me to, that would
be fantastic as well.
Thanks in advance.
Randy
- 4
- Changing log level at runtimeYou know the situation: logging output is useless .. until you need it.
Is there a way to configure log4j in a web application or an EJB with
log level ERROR and have it change to DEBUG whenever an error happens?
The only thing I can imagine is having a special servlet that you have
to call with the browser to have it trigger a log level change for the
whole web application.
Are there better ways? Maybe with the jdk built-in logger?
Or with log4j JMX? But I could not find any docs or examples.
Thx,
Juergen
- 5
- Hot-deployment of EAR/JAR files using classloaders (on JBoss app server)Hi,
I am trying the following scenario:
- I deploy an app.ear into the jboss server.
- app.ear invokes a session bean deployed separately (sessionbean.jar)
- everything works fine
- I modify sessionbean.jar
- I redeploy it without restarting the server (hot deployment)
When app.ear invokes the sessionbean, it refers to the previous instance of
the sessionbean. And because I have replaced it, it does not find the
class...
Then I read on, and I find that if you write custom class loaders, you can
load new versions of classes on the fly (dynamic loading).
So I wrote a custom class loader, which works fine when I call a basic java
library, but there does not seem to be a way of 'redeploying' this
sessionbean.jar as a bean (you can't invoke it anymore with the home/remote
interface)....
Can someone help me here ? I am basically trying to redeploy beans without
redeploying the app server and having them immediately rebind to whichever
application needs to use them.
Thanks
Steph
- 6
- Problem starting out with Java . . .Hey. Im new to Java, and am having a prroblem with the netbeans IDE.
every time i try to import java.awt.* , I can't use any of the
methods(like they don't exist). I can compile it fine, but when I try to
run it, I get "exception in class main".
Can anyone help me, please?
- 7
- Implementing an interface in eclipseUsing IntelliJ, I would be able to implement an interface whilst having
it open in the editor. You could open the context window using the
keyboard and choose to implement interface and magically the
implementation appears complete with the statement "... implements
SomeInterface"
Does anyone know how to do the same in eclipse so I don't have to open
that New Class window and manually choose the interface?
- 8
- Override prepareRenderer()I've gathered that in order to change the background color of a row,
one can either use the tablecellrenderer or can override the
prepareRenderer() method. I have chosen to override the
prepareRenderer() method. My question (and a reather silly one) is
exactly how to call this method to then color your rows.
I already have a jtable with is autogenerated by netbeans and all of
the code I've seen, the jtable is created programmatically.
Here is what I TRIED to do (any help is greatly appreciated):
public void updateGUI(String newValue){
DefaultTableModel errorTableModel = (DefaultTableModel)
parentScreen.jTableErrors.getModel();
int numRows = errorTableModel.getRowCount();
numRows++;
errorTableModel.setRowCount(numRows);
parentScreen.jTableErrors.setModel(errorTableModel);
Object newObjectError = (Object) newValue;
parentScreen.jTableErrors.setValueAt(newObjectError, numRows - 1, 0);
JTable coloredTable = new JTable( errorTableModel )
{
public Component prepareRenderer(
TableCellRenderer renderer, int row, int column)
{
Component c = super.prepareRenderer(renderer, row, column);
String message = (String) getValueAt(row, column);
String[] dividedMsg = message.split(":");
if(dividedMsg[0].equals("Error: ")){
this.setBackground(Color.RED);
}
else{
this.setBackground(Color.YELLOW);
}
return c;
}
};
parentScreen.jTableErrors = coloredTable;
}
- 9
- How to simulate a busy taskHi everybody,
I was trying to perform some tests in a multithreading application and
I would like to simulate overloading. That is, I want to simulate
threads performing a task that takes a certain time T. I have thought
of the following possibilities:
-Implement a method that sleeps during T milliseconds. Problem: this
does not overload the computer, during those T milliseconds other
agents can execute.
-Implement a method that performs a busy wait (while(true){...}) and
exits when T milliseconds have passed. Problem: there could be context
switches in between, and so it could happen that another thread
executes in the meantime (and that execution time should not count to
decide when to terminate the busy wait).
-Similar to the previous approach, but we try to count the milliseconds
elapsed "by hand". That is, in every iteration we obtain the
System.currentTimeMillis() and count as much as 1 millisecond (if it is
really at least 1 millisecond greater than the value measured in the
previous iteration). In this way, if the thread is interrupted while
executing the method, nothing happens because we count at most 1
millisecond per iteration. This does not work either too well, because
more than 1 millisecond could have been elapsed between measures.
So I'm not really sure if I can do this with some precision. If you
have any suggestions, please let me know. Thanks in advance,
S.
- 10
- 11
- please explain this simple constructmy instructor likes to use this construct in class but never really
explained why/how it works:
while (true)
{
if (something) return; // break from while
}
can someone shed some light how this works?
- 12
- getDocumentBase and getCodeBase not recognized...Hi, Im having a slight problem.
I am trying to load an image object with the code below, and I am NOT
extending Applet in my class because I am working on an application.
The problem is that getCodeBase AND getDocumentBase are not being
recognized by my application, however I am sure that the required jars
are in the build path... and that I've referenced them... most likely
inapproprirately.
My code is set up like this
Base\
Base\graphics\img.gifs.
Code follows, I trimmed the imports mostly off, but the rest appear
below the code...
Thanks for your advice.
import java.net.URL;
import java.applet.Applet;
............
String strImageUp = "graphics/up.gif";
URL urlUp = getClass().getResource(strImageUp);
Image imgUp = null;
try {
MediaTracker m = new MediaTracker(this);
imgUp = getImage(getDocumentBase(), strImageUp);
m.addImage(imgUp, 0);
m.waitForAll();
}
catch (Exception e) {
e.printStackTrace();
}
................
import javax.crypto.interfaces.PBEKey;
import javax.imageio.*;
import java.awt.image.*;
import java.io.File;
import java.io.IOException;
import java.util.Vector;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.Border;
import java.util.LinkedList;
import java.util.ListIterator;
import java.awt.event.ActionListener; //for buttons
import java.awt.event.ActionEvent; //for button events
import java.awt.event.KeyEvent; //for key shortcuts
import java.math.*; //percentage rounding
- 13
- poster or wallpaperHi all
I need posters or wallpapers which is about programming and computer
science, for hanging
thanks
- 14
- hide NullPointerExceptionI have a GUI which throws a nullpointerexception when things go wrong.
Then it closes. That nullpointerexception is expected and I want it
ignored since before that it has already informed the user that
something has gone wrong and its closing. How can I do this? If I just
put the part of the function throwing the exception within try/catch,
it tends to hang. If I leave it as is, it throws the exception but
closes fine. I just don't want the user to see that exception.
- 15
- Q: Possible to auto-fallback back to MS JVM from Sun JVM ?Hi all.
Ok, so it's no secret, MS can no longer distribute its Java VM with
its OS'.
Naturally, that didn't stop me from installing an old one so
WindowsUpdate would see it and upgrade it to the last (MS) build:
5.00.3810
I also installed the latest SUN Java VM (1.4.2_03)
*** Flash ***
Woaaaah!! Just saw their "Law & Order" game
(http://java.com/en/index.jsp)
Gotta try that!
*** End Flash ***
So what I want in fact, is to use SUN's VM as default, but to
automatically switch back to MS' VM for those sites that still use it
(for example, my bank still uses it, so I can't issue payments if Sun
is default -- annoying).
Of course, this can be done manually in "Set Program Access and
Defaults" in hte Window scontrol panel, but you have to select one or
the other.
Same with Sun's Java Plug-in control panel (Advanced tab).
So... is there a way to perform an auto-fall-back to MS JVM when an
applet cannot load/initialise with the Sun JVM ?
Or create a list of site which must use MS instead of Sun?
Any help appreciated.
M.T.
|
|
|