简体   繁体   English

Java String最佳做法

[英]Java String best practices

I have 4 String parameter's in Java (from request object) 我在Java中有4个String参数(来自请求对象)

String dd = req.getParameter(dd);
String mm = req.getParameter(mm);
String yyyy = req.getParameter(yyyy);

after validating dd,mm,yyyy I am building date object in 4th String variable by building String date = dd+"/"+mm+"/"+yyyy; 验证dd,mm,yyyy之后,我通过构建String date = dd+"/"+mm+"/"+yyyy;在第四字符串变量中构建日期对象String date = dd+"/"+mm+"/"+yyyy; again in some places i need to replace the date format as following, 再次在某些地方,我需要按以下方式替换日期格式,

date = yyyy+mm+dd;
date =mm+"/"+dd+"/"+yyyy;  // storing in db need this format

How much memory would consume since 4 objects need to pass till persist in table? 由于需要传递4个对象直到保留在表中,因此会消耗多少内存? Was it costlier memory call? 是更昂贵的内存调用吗? Is there any best practice? 有没有最佳做法? At last howmany string objects would be in Stringpool? 最后,在Stringpool中有多少个字符串对象?

My suggestion is that you should not be worry about micro improvement as other also suggested. 我的建议是,您不应像其他建议那样担心微改进。 May be create a wrapper object eg MyDate and construct Date object once. 可以创建一个包装对象,例如MyDate并构造一次Date对象。 After that you can use different formatter to format your date. 之后,您可以使用其他格式化程序格式化日期。

package com.dd;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.joda.time.LocalDate;

public class MyDate {

    private Date date;

    public MyDate(Request req) {
        int day = req.getParameter("dd");
        int month = req.getParameter("mm");
        int year = req.getParameter("yyyy");
        date = new LocalDate(year, month, day).toDate();
    }

    public String format(String givenFormat) {
        SimpleDateFormat sdf = new SimpleDateFormat(givenFormat);
        return sdf.format(date);
    }

}

Note - You need to confirm and validate what values you're getting from your request and if they are in same notation as expected by LocalDate 注意-您需要确认并验证从请求中获取的值,以及它们是否与LocalDate期望的表示法相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM