`
major361
  • 浏览: 31824 次
  • 性别: Icon_minigender_1
  • 来自: 福州->杭州
社区版块
存档分类
最新评论

String I/O Parse etc.

阅读更多
一、The differences between the String, StringBuilder, and StringBuffer classes
1.Strings are immutable
String s = "abcde";
s = s.concat("more stuff");


Now there are three String Objects
abcde、more stuff、 abcde more stuff

2.To make Java more memory efficient, the JVM sets aside a special area of memory called the "String constant pool."

When the compiler encounters a String literal, it checks the pool to see if an identical String already exists. If a match is found, the reference to the new literal is directed to the existing String, and no new String literal object is created.

3.Create new strings
   String s="abc"                //create one String Object(in pool)
   String s= new String("abc");  //create two String 
objects,one in "String pool",and another in normal memory

4.StringBuilder is not safe thread because its method is not synchronize , but run faster than StringBuffer
      public synchronized StringBuffer append(String s)

二.Calendar主要用于日期的操纵,它是一个抽象类,所以
Calendar c = new Calendar();   //非法
Calendar c = Calendar.getInstance()  //合法
//当日期为2001年10月,此时调用
c.roll(Calendar.MONTH,9);
//此时日期为2001年7月,它只会改变日期,但不进位(即不改变年份)


三.DateFormat的用法
import java.text.*;
import java.util.*;
class Dates3 {
public static void main(String[] args) {
Date d1 = new Date(1000000000000L);
DateFormat[] dfa = new DateFormat[6];
dfa[0] = DateFormat.getInstance();
dfa[1] = DateFormat.getDateInstance();
dfa[2] = DateFormat.getDateInstance(DateFormat.SHORT);
dfa[3] = DateFormat.getDateInstance(DateFormat.MEDIUM);
dfa[4] = DateFormat.getDateInstance(DateFormat.LONG);
dfa[5] = DateFormat.getDateInstance(DateFormat.FULL);
for(DateFormat df : dfa)
System.out.println(df.format(d1));
}
}
//which on our JVM produces
9/8/01 7:46 PM
Sep 8, 2001
9/8/01
Sep 8, 2001
September 8, 2001
Saturday, September 8, 2001


如果我们把日期转化为SHORT型,然后在parse为日期,此时会丢失精度
Date d1 = new Date(1000000000000L);
System.out.println("d1 = " + d1.toString());
DateFormat df = DateFormat.getDateInstance(
DateFormat.SHORT);
String s = df.format(d1);
System.out.println(s);
try {
Date d2 = df.parse(s);
System.out.println("parsed = " + d2.toString());
} catch (ParseException pe) {
System.out.println("parse exc"); }
//which on our JVM produces
d1 = Sat Sep 08 19:46:40 MDT 2001
9/8/01
parsed = Sat Sep 08 00:00:00 MDT 2001



四.正则表达式的使用
import java.util.regex.*;
class RegexSmall {
public static void main(String [] args) {
Pattern p = Pattern.compile("ab"); // the expression
Matcher m = p.matcher("abaaaba"); // the source
boolean b = false;
while(b = m.find()) {
System.out.print(m.start() + " "+m.group());
//调用group()方法获得匹配的结果
}
}
}


五、习题中出现的错误
1.Remember, that the equals() method for the integer wrappers
will only return true if the two primitive types and the two values are equal.
class TKO {
public static void main(String[] args) {
String s = "-";
Integer x = 343;
long L343 = 343L;
if(x.equals(L343)) s += ".e1 ";
if(x.equals(343)) s += ".e2 ";
Short s1 = (short)((new Short((short)343)) / (new Short((short)49)));
if(s1 == 7) s += "=s ";
if(s1 < new Integer(7+1)) s += "fly ";
System.out.println(s);
} }


2.The %b (boolean) conversion character returns true for any
non-null or non-boolean argument.

System.out.format("%b", 123);


the %f (floating-point) conversion character won't automatically promote an integer type

System.out.printf("%f", 123);  //illegal


3.Only String objects can be operated on using the overloaded "+" operator.

StringBuffer sb = new StringBuffer("hello");
		sb += "xyz";  //illegal


-------------------------------------------------------
New words in this chapter
1.zillion    n.    庞大的数字、无法计算的数字
2.budge      v.    移动
3.devilish   adj.  如恶魔般的,精力旺盛的
4.concordant adj.  协调的
5.cohesion   n     结合,凝聚,内聚
6.lenient    adj.  宽大的,仁慈的
7.newbie     n     新手
8.guru       n     领袖,头头
9.chunk (of) n.    大块,矮胖的人或物
10.maven     n.    内行,专家
分享到:
评论

相关推荐

    lunch_cb5801_r58_20160907.7z

    ./recovery/Android.mk:ifneq (,$(findstring $(TARGET_DEVICE),octopus-perf)) ./recovery/Android.mk:LOCAL_MODULE := librecovery_ui_octopus_perf ./recovery/Android.mk:LOCAL_MODULE := librecovery_updater_...

    lunch_r58_20160906.7z

    ./recovery/Android.mk:ifneq (,$(findstring $(TARGET_DEVICE),octopus-perf)) ./recovery/Android.mk:LOCAL_MODULE := librecovery_ui_octopus_perf ./recovery/Android.mk:LOCAL_MODULE := librecovery_updater_...

    v8-argv:将 v8 argv(包括和声)代理到 v8node,同时将其余参数转发到自定义脚本

    v8-argv 将 v8 argv(包括和声)代理到 v8/node,同时将其余参数转发到自定义脚本。安装v8-argv在上可用。 npm install v8-argv用法@param {String}解析为实际 bin 的路径... // etc...测试 npm test信用到期 by 执照

    CentOS7.2.1511 gcc4.8.5 通过编译的 tfs2.2.16

    [root@2f60c4bcddfa tfs_release-2.2.16]# ./configure --prefix=/usr/local/ configure ok make 问题 : serialization.h:575:27: error: conversion to 'char' from 'long int' may alter its value [-Werror=...

    uptime指令的简单实现

    - `/proc/time`或`/etc/timezone`:获取当前时区和时间。 接下来,让我们详细讲解如何用C语言来读取这些文件并解析数据。 1. **读取/proc/uptime**: 这个文件包含两部分浮点数,分别表示系统总运行时间(秒)和...

    php.ini-development

    An empty string can be denoted by simply not writing anything after the equal ; sign, or by using the None keyword: ; foo = ; sets foo to an empty string ; foo = None ; sets foo to an empty string ;...

    Linux下安装protobuf教程

    ./configure --prefix=/usr/local/protobuf make make check make install ``` 5. 配置环境变量 ``` sudo vim /etc/profile ``` 添加以下两行代码: ``` export PATH=$PATH:/usr/local/protobuf/bin export PKG_...

    android2.3.5 CDMA/EVDO拨号APN解决方案

    此外,还需要更新`development/data/etc/apns-conf.xml`文件中的`version`值,将其增加1,以确保系统识别到配置文件的更改。 完成以上步骤后,CDMA/EVDO用户将能够在系统设置中找到并管理多个APN账户,与GSM/WCDMA...

    北大天网搜索引擎TSE源码

    One is for ImgSE whose urls must include "tupian", "photo", "ttjstk", etc. the other is for normal crawling. For ImgSE, remember to comment the paragraph and choose right "CPage::IsFilterLink(string ...

    android当前apn的状态以及获取方法

    在Android系统中,APN配置通常存储在`/etc/apns-conf.xml`文件中,这个文件包含了设备上可用的APN设置。然而,由于安全原因,该文件通常被保护,只有在设备获得root权限后才能直接查看或修改。 要获取Android设备...

    parse-path:解析路径(本地路径、url

    解析路径(本地路径,urls:ssh/git/etc) :cloud: 安装 # Using npm npm install --save parse-path # Using yarn yarn add parse-path :clipboard: 例子 // Dependencies const parsePath = require ( "parse...

    node-parse-buffer:从缓冲区转换为对象

    节点解析缓冲区 解析缓冲区 从缓冲区转换为对象。 解析缓冲区 安装 npm install parse-buffer 例子 var parser = require ( 'parse-buffer' ) ;... { etc : p . value ( '' ) } ) ) } , { message2 : p . option

    轻量级JSON解析库Brief-JSON.zip

    序列化流程JSON TEXT &lt;====jsonserializer=====&gt;Map,List,String,etc. &lt;====beanserializer====&gt;JAVA BEANBeanSerializer.deserializer :把List和Map反序列化为Java Bean;JSONSerializer.serializer :把List和Map...

    proc oracle 示例

    可以在/etc/profile 文件中添加以下内容: `LD_LIBRARY_PATH=$ORACLE_HOME/lib:/usr/lib:/usr/local/lib` `export LD_LIBRARY_PATH` 配置 pcscfg.cfg 文件 pcscfg.cfg 文件位于 $ORACLE_HOME/precomp/admin/ 目录...

    Functional Programming

    According to the platform, fold is also known as reduce, aggregate, accumulate, etc. #### Formal Description Assume: - `T` is the type of the elements in the input sequence. - `U` is the type of the...

    在jdk5中使用JSR105实现XML签名认证的解决方案

    PrivateKey privateKey = KeyStoreInfo.getPrivateKey("./etc/bizkeystore", "sp1234", "kp1234", "biz"); ``` - **情形5.1**:使用自动生成的密钥对或者从密钥存储中获取密钥对。 - **情形5.1.1**:生成密钥对。...

    acpi控制笔记本风扇转速

    produced when this parameter was a null string (""). Now, the original input filename is used as the AML output filename, with an ".aml" extension. Implemented a generic batch command mode for the ...

    Lerner -- Python Workout. 50 Essential Exercises -- 2020.pdf

    - **Objective:** Parse the `/etc/passwd` file and convert it into a dictionary. - **Key Concepts:** - File parsing using regular expressions. - Creating dictionaries from parsed data. 20. **Word ...

Global site tag (gtag.js) - Google Analytics